Covers WireMock.Net as a real HTTP stub server for outbound calls: request matching, JSON responses, delays, faults and stateful scenarios, wiring the base URL into WebApplicationFactory, verifying requests from the log, and testing resilience pipelines.
WireMock.Net (Apache 2.0) starts a real HTTP server on a random port inside the test. You configure stubs with server.Given(Request.Create().WithPath("/v1/rates").UsingGet()).RespondWith(Response.Create().WithStatusCode(200).WithBodyAsJson(...)), then point the app's typed HttpClient at server.Url through configuration, for example with UseSetting in WebApplicationFactory.
For failure modes:
.WithDelay(TimeSpan.FromSeconds(5)) to prove timeouts fire.Retry-After, and stateful scenarios (fail, fail, succeed) to test retries..WithFault(FaultType.MALFORMED_RESPONSE_CHUNK) or an empty response.Verify what was sent with server.LogEntries. The trade-off: you test the real HTTP pipeline and resilience policies, but the stub only matches the provider as well as you wrote it, so pair it with contract tests or a sandbox check.
"For outbound HTTP I don't mock
HttpClientor the typed client interface in integration tests, because then my serialisation, headers,DelegatingHandlers and resilience pipeline never run. Instead I start WireMock.Net, which is a real HTTP server running inside the test process on a random port. I stub the endpoints the provider has, point my app's base URL atserver.Urlthrough configuration, and the app makes genuine HTTP calls over loopback.That's what makes failure testing possible. I can say: the first two calls return 503, the third returns 200, using WireMock's scenario states, and assert that my standard resilience handler retried and the user got a 200. I can add a five-second
WithDelayand prove my attempt timeout fires and we return a clean ProblemDetails instead of hanging a request thread. I can return a malformed chunk or invalid JSON and check we log and degrade rather than throw a 500. And afterwards I readserver.LogEntriesto assert we sent the right API key header, an idempotency key on POSTs, and didn't call the provider more times than we should. For example, at [company] we [found that a retry policy was retrying non-idempotent POSTs to a payment provider]; a WireMock test that counted requests exposed it [before go-live].I run WireMock in-process with
WireMockServer.Start()for speed, or as a container with Testcontainers when other services need to call it too. The mistake I see is stubs drifting from the real API: I keep stub payloads as JSON files copied from the provider's documentation or sandbox, and back them up with a contract or sandbox smoke test."
| Need | API |
|---|---|
| Start | WireMockServer.Start() (random port), server.Url |
| Match | Request.Create().WithPath("/x").UsingPost().WithHeader("Authorization", "*", MatchBehaviour.AcceptOnMatch).WithBody(new JsonPartialMatcher(...)) |
| Respond | Response.Create().WithStatusCode(200).WithBodyAsJson(obj).WithHeader(...) |
| Slow | .WithDelay(TimeSpan.FromSeconds(5)) or .WithRandomDelay(100, 2000) |
| Broken | .WithFault(FaultType.MALFORMED_RESPONSE_CHUNK) / FaultType.EMPTY_RESPONSE |
| Sequence | .InScenario("retry").WhenStateIs(...).WillSetStateTo(...) |
| Verify | server.LogEntries, server.FindLogEntries(request) |
| Reset | server.Reset() / ResetMappings() / ResetLogEntries() |
| Provider behaviour | What to assert |
|---|---|
| 503 then 200 | Retried, user sees success, request count = 2 |
429 with Retry-After |
Back-off honoured, no retry storm |
| Slow beyond attempt timeout | Timeout fires; total time under budget |
| 400 with error body | Mapped to a meaningful ProblemDetails, not 500 |
| Malformed or empty body | Logged, degraded, no unhandled exception |
| POST failure | Not retried unless idempotent (idempotency key sent) |
A quoting service called a freight API with a total timeout of 100 seconds (the HttpClient default). WireMock tests with a 30-second delay showed request threads piling up; after adding AddStandardResilienceHandler with a 2-second attempt timeout and a fallback price, P99 latency during the provider's next outage stayed at 2.4 seconds instead of timing out at the gateway.
Checks whether the candidate tests outbound integrations realistically, including failure modes and resilience behaviour.
Green flags
Red flags
Your code -> typed client -> DelegatingHandlers -> resilience handler -> SocketsHttpHandler
|
TCP loopback
v
WireMock.Net server
Mocking IRatesClient skips everything to the right of your code. Mocking HttpMessageHandler skips sockets and timeouts. WireMock keeps the entire chain, so timeouts, retries, decompression, headers and serialisation are all real.
Each mapping has a request matcher and a response. WireMock scores incoming requests against all mappings and picks the best match (with priority as a tie-breaker). Matchers include exact, wildcard, regex, JSON path, JsonPartialMatcher (body contains these fields) and custom functions. Unmatched requests get a 404 and are recorded, which is a quick way to discover calls you didn't expect.
WithDelay holds the response, which tests attempt timeouts and cancellation. WithFault deliberately breaks the HTTP response (MALFORMED_RESPONSE_CHUNK sends a 200 header with broken chunked body; EMPTY_RESPONSE closes the connection). These reproduce the HttpRequestException and IOException errors you see in production when a provider or proxy misbehaves.
A scenario is a named state machine. Each mapping can require a state and move to another:
Started --(503)--> first-failed --(503)--> second-failed --(200)--> ...
This is how you test "retry twice then succeed" deterministically.
Microsoft.Extensions.Http.Resilience AddStandardResilienceHandler adds rate limiting, a total timeout (30 s by default), retries (3 with exponential back-off and jitter), a circuit breaker and an attempt timeout (10 s by default). In tests, shorten these through options so a retry test takes milliseconds, not seconds, and use FakeTimeProvider where the policy accepts a TimeProvider.
In-process WireMockServer is fastest and easiest to debug. WireMock.Net also ships a Docker image (usable from Testcontainers) when several services, a browser or a non-.NET process must call the stub. Admin API endpoints let you configure mappings over HTTP or from JSON files.
WithDelay(5s) and an attempt timeout of 1 s; assert a TimeoutRejectedException or your fallback.FaultType.EMPTY_RESPONSE and see which exception your code gets.LogEntries that every POST carried an Idempotency-Key header.A typed client with a resilience handler, and WebApplicationFactory tests that point it at WireMock.Net for success, retry and timeout cases:
// Program.cs (code under test, abbreviated)
using System.Net.Http.Json;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<RatesClient>(c =>
c.BaseAddress = new Uri(builder.Configuration["Rates:BaseUrl"]!))
.AddStandardResilienceHandler(o =>
{
// Values come from config so tests can shrink them.
o.AttemptTimeout.Timeout = TimeSpan.FromMilliseconds(builder.Configuration.GetValue("Rates:AttemptTimeoutMs", 2000));
o.Retry.Delay = TimeSpan.FromMilliseconds(builder.Configuration.GetValue("Rates:RetryDelayMs", 200));
});
var app = builder.Build();
app.MapGet("/quotes/{currency}", async (string currency, RatesClient rates, CancellationToken ct) =>
{
try { return Results.Ok(new { currency, rate = await rates.GetRateAsync(currency, ct) }); }
catch (Exception ex) when (ex is HttpRequestException or Polly.Timeout.TimeoutRejectedException)
{
return Results.Problem("Rates provider unavailable", statusCode: 503);
}
});
app.Run();
public sealed record RateDto(string Currency, decimal Rate);
public sealed class RatesClient(HttpClient http)
{
public async Task<decimal> GetRateAsync(string currency, CancellationToken ct) =>
(await http.GetFromJsonAsync<RateDto>($"/v1/rates/{currency}", ct))!.Rate;
}
// RatesTests.cs (xunit.v3, WireMock.Net, Microsoft.AspNetCore.Mvc.Testing)
using System.Net;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
using Xunit;
namespace Quotes.Api.Tests;
public sealed class RatesApiFactory : WebApplicationFactory<Program>
{
public WireMockServer Rates { get; } = WireMockServer.Start(); // random port
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseSetting("Rates:BaseUrl", Rates.Url!);
builder.UseSetting("Rates:AttemptTimeoutMs", "300"); // keep timeout tests fast
builder.UseSetting("Rates:RetryDelayMs", "10");
}
public override async ValueTask DisposeAsync()
{
Rates.Stop();
await base.DisposeAsync();
}
}
public sealed class RatesTests : IClassFixture<RatesApiFactory>
{
private readonly RatesApiFactory _factory;
private readonly HttpClient _client;
public RatesTests(RatesApiFactory factory)
{
_factory = factory;
_factory.Rates.Reset(); // mappings and logs are per test
_client = factory.CreateClient();
}
[Fact]
public async Task Returns_rate_from_provider()
{
_factory.Rates.Given(Request.Create().WithPath("/v1/rates/AUD").UsingGet())
.RespondWith(Response.Create().WithStatusCode(200).WithBodyAsJson(new { currency = "AUD", rate = 0.65m }));
var response = await _client.GetAsync("/quotes/AUD", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Single(_factory.Rates.LogEntries); // exactly one outbound call
}
[Fact]
public async Task Retries_transient_503_then_succeeds()
{
const string scenario = "flaky";
_factory.Rates.Given(Request.Create().WithPath("/v1/rates/NZD").UsingGet())
.InScenario(scenario).WillSetStateTo("failed-once")
.RespondWith(Response.Create().WithStatusCode(503));
_factory.Rates.Given(Request.Create().WithPath("/v1/rates/NZD").UsingGet())
.InScenario(scenario).WhenStateIs("failed-once")
.RespondWith(Response.Create().WithStatusCode(200).WithBodyAsJson(new { currency = "NZD", rate = 0.59m }));
var response = await _client.GetAsync("/quotes/NZD", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Equal(2, _factory.Rates.LogEntries.Count());
}
[Fact]
public async Task Slow_provider_returns_503_problem_instead_of_hanging()
{
_factory.Rates.Given(Request.Create().WithPath("/v1/rates/USD").UsingGet())
.RespondWith(Response.Create().WithStatusCode(200).WithDelay(TimeSpan.FromSeconds(5)));
var started = DateTime.UtcNow;
var response = await _client.GetAsync("/quotes/USD", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
Assert.True(DateTime.UtcNow - started < TimeSpan.FromSeconds(3)); // attempt timeouts fired
}
}
HttpClient pipeline executes.WireMockServer.Start() with a random port and pass server.Url through configuration.Reset() in the test constructor or use a server per class.LogEntries, or disable retries for unsafe methods.Outbound dependencies are where most production incidents start, and WireMock.Net is the cheapest way to rehearse them. I treat each third-party integration as needing a small failure matrix (slow, 5xx, 429, malformed, 4xx) tested through the real HttpClient pipeline, and the resilience settings as code that must be tested like any other.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| WireMock.Net in-process | Integration tests of one service's outbound calls | Stubs to maintain | Proving the provider's real behaviour |
| WireMock.Net container | Several processes or a browser need the stub | Docker, slower start | Single-service tests |
Stub HttpMessageHandler |
Unit-testing a client class's parsing | Skips sockets and timeouts | Testing resilience policies |
| Provider sandbox | Final confidence in the real contract | Slow, rate-limited, flaky | Every PR |
| Pact contract tests | Internal services you both own | Broker and process | Third-party APIs you don't control |
Measure by injecting the same faults in a staging chaos test and checking that latency and error rates match what the WireMock tests predicted.
Point the typed HttpClient at a WireMock.Net server in the test and configure it to return 500s, 429s with Retry-After, or delayed responses. Then assert your API's behaviour: the resilience pipeline (AddStandardResilienceHandler) retries the right number of times, the timeout fires, the circuit breaker opens, and the endpoint returns a sensible ProblemDetails (502 or 503) instead of hanging. Use FakeTimeProvider where possible so retries and timeouts don't make the test slow, and check WireMock's request log to count retries.
Add Microsoft.Extensions.Http.Resilience and call AddStandardResilienceHandler() on the HttpClient registration. It builds a Polly v8 pipeline. From outside in:
Retry-After),Use Retry.DisableForUnsafeHttpMethods() so POST and PATCH aren't retried. Retrying them blindly can charge a customer twice unless the API supports an idempotency key.
Test it with WireMock.Net: a scenario that returns 503, 503, then 200, and WithDelay for timeouts. Shrink the delays and thresholds in the test. The trade-off is that retries hide brief failures but add load and latency, so the total timeout has to cap them.
How to tell it (STAR)
**S:** At [company] our quoting API slowed to a crawl when the freight provider degraded at [month-end]. **T:** I led the fix and making sure a slow provider couldn't take us down again. **A:** I found we were waiting the default 100 seconds per call, reproduced it with WireMock.Net delays in our integration tests, then added attempt timeouts, a circuit breaker and a cached fallback, with tests for slow, failing and malformed responses. **R:** During the provider's next outage our P99 stayed at about [2.4 s], we served [98%] of quotes from the fallback, and there were no gateway timeouts.
Last updated 23 Nov 2026.