Create the TwilioRestClient with an HttpClient whose handler rewrites the host to https://api.otpmock.com and keeps the path, query and auth header. Use your otpmock API key as the Twilio auth token. Your sending code (MessageResource.CreateAsync, Twilio Verify) does not change. In the test, poll the inbox's HTTP API for the code. Production keeps the default client because the handler is only used when OTPMOCK_URL is set.
Why Twilio's own test credentials are not enough
Twilio's test credentials and "magic" numbers return canned responses: nothing is delivered, you cannot read the message body or code, and Twilio Verify is not covered. That is fine for checking that your code builds a valid request, and useless for an end-to-end test that has to type the code back in. See Twilio test credentials: limits and alternatives for the details.
Step 1: route the Twilio SDK to the mock
The handler below is the tested approach: it swaps the scheme and host of each outgoing request and leaves everything else alone, so the SDK's paths, query strings and Basic auth header reach otpmock untouched.
using Twilio.Clients;
using Twilio.Http;
// Sends requests to otpmock, keeping path, query and auth headers.
class OtpMockHandler : DelegatingHandler
{
private readonly Uri _base;
public OtpMockHandler(string baseUrl) : base(new HttpClientHandler()) => _base = new Uri(baseUrl);
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken ct)
{
request.RequestUri = new Uri(_base, request.RequestUri!.PathAndQuery);
return base.SendAsync(request, ct);
}
}Then build the client, using the mock only when OTPMOCK_URL is set:
var otpmock = Environment.GetEnvironmentVariable("OTPMOCK_URL");
var client = new TwilioRestClient(
accountSid,
authToken, // otpmock API key in tests
httpClient: otpmock is null ? null : new SystemNetHttpClient(new HttpClient(new OtpMockHandler(otpmock))));
// Pass it to each call:
// await MessageResource.CreateAsync(to: ..., from: ..., body: ..., client: client);
// Or register it once for the static API: TwilioClient.SetRestClient(client);In the test environment set OTPMOCK_URL=https://api.otpmock.com and put your otpmock API key where the Twilio auth token normally goes. The account SID can stay as it is; otpmock echoes it back. Set these on the process that runs your application, because the app, not the test, sends the SMS.
Step 2: a helper that reads the code
The inbox API returns the newest code sent to a number after a timestamp, or 404 if none has arrived yet. A short polling helper is all a .NET test needs:
using System.Net.Http.Headers;
using System.Text.Json;
public sealed class OtpMockInbox
{
private readonly HttpClient _http;
public OtpMockInbox(string baseUrl, string apiKey)
{
_http = new HttpClient { BaseAddress = new Uri(baseUrl) };
_http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
}
// A unique number per test, so parallel tests never read each other's codes.
public static string RandomPhone() => "+1555" + Random.Shared.Next(0, 10_000_000).ToString("D7");
public async Task<string> WaitForCodeAsync(string phone, DateTimeOffset since, TimeSpan? timeout = null)
{
var deadline = DateTime.UtcNow + (timeout ?? TimeSpan.FromSeconds(15));
var url = $"/v1/inbox/{Uri.EscapeDataString(phone)}/code?since={since.ToUnixTimeMilliseconds()}";
while (true)
{
using var res = await _http.GetAsync(url);
if (res.IsSuccessStatusCode)
{
using var doc = await JsonDocument.ParseAsync(await res.Content.ReadAsStreamAsync());
return doc.RootElement.GetProperty("code").GetString()!;
}
if ((int)res.StatusCode != 404) throw new InvalidOperationException($"otpmock returned {(int)res.StatusCode}");
if (DateTime.UtcNow >= deadline) throw new TimeoutException($"No code arrived for {phone}");
await Task.Delay(300);
}
}
}Step 3: an xUnit test
This smoke test proves the routing works end to end: it sends through the Twilio SDK and reads the code back.
using Twilio.Rest.Api.V2010.Account;
using Twilio.Types;
using Xunit;
public class TwilioRoutingTests
{
[Fact]
public async Task Sms_sent_through_the_twilio_sdk_lands_in_the_inbox()
{
var inbox = new OtpMockInbox("https://api.otpmock.com", Environment.GetEnvironmentVariable("OTPMOCK_API_KEY")!);
var phone = OtpMockInbox.RandomPhone();
var since = DateTimeOffset.UtcNow.AddSeconds(-5); // margin for clock skew
await MessageResource.CreateAsync(
to: new PhoneNumber(phone),
from: new PhoneNumber("+15005550006"),
body: "Your code is 482913",
client: TestClients.Twilio); // the TwilioRestClient from step 1
Assert.Equal("482913", await inbox.WaitForCodeAsync(phone, since));
}
}In a real suite the SMS is sent by your application (for example a controller exercised through WebApplicationFactory), and the test only triggers it and then reads the code with WaitForCodeAsync.
Twilio Verify in .NET
With Twilio Verify the provider normally generates the code, so a fake sender would never see it. otpmock emulates Verify v2: it generates the code, your test reads it from the inbox, and the check call approves it exactly as Twilio would, including how wrong codes and the attempt limit are reported.
var since = DateTimeOffset.UtcNow.AddSeconds(-5);
await VerificationResource.CreateAsync(to: phone, channel: "sms", pathServiceSid: serviceSid, client: client);
var code = await inbox.WaitForCodeAsync(phone, since);
var check = await VerificationCheckResource.CreateAsync(pathServiceSid: serviceSid, to: phone, code: code, client: client);
Assert.Equal("approved", check.Status);The same OtpMockHandler and client cover both Messaging and Verify, because both use the same host rewrite.
Common pitfalls
- Setting the variable only on the test runner. The application sends the SMS, so
OTPMOCK_URLand the otpmock key must be set where the app runs. - Forgetting to pass the client.
MessageResource.CreateAsyncuses the static default client unless you passclient:or callTwilioClient.SetRestClient. - Taking
sinceafter the call. Note the time before the action that sends the SMS, minus a few seconds for clock skew. - Sharing one phone number across tests. Use a unique number per test, so parallel xUnit collections do not read each other's codes.
- Disposing the
HttpClientper request. Create the Twilio client once and reuse it.
FAQ
Does the Twilio .NET SDK have a base URL option?
No. That is why the handler rewrites the host. It keeps the path, query string and Basic auth header, so Twilio's own request format reaches otpmock unchanged.
Does this work with Twilio Verify as well as plain SMS?
Yes. Twilio Verify v2 is emulated, including the code check, wrong-code errors and the attempt limit. See the Twilio Verify guide.
Will my production traffic go through otpmock?
No. The handler is only used when OTPMOCK_URL is set, which you do in test and staging environments. Production keeps the default Twilio client and sends real SMS.
The free plan includes 300 messages a month. No card required.
Get a free API key