Lesson 81 of 93 · 6 min read · Updated

Simulating External APIs with WireMock.Net in ASP.NET Core Integration Tests

Most applications call other services over HTTP. In tests you cannot depend on those services: they may be slow, down, rate-limited or return different data every day. A common workaround is to mock the client interface, but then the real HttpClient code never runs. WireMock.Net takes a different approach. It starts a real HTTP server inside the test process, and you program its responses. This lesson shows how to point an API at WireMock.Net and test success, error mapping, latency and multi-step scenarios.

Technical Requirements

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. WireMock.Net 2.31.0
  4. Microsoft.AspNetCore.Mvc.Testing 11.0.0
  5. FluentAssertions 7.2.2
  6. Docker is not required. WireMock.Net runs in process.

The Client Under Test

The Books API converts a book's price into a foreign currency. It asks an external rate service for the exchange rate through a typed HttpClient:

M09.IntegrationApi/External/CurrencyClient.cs

/// <summary>
/// EXTERNAL HTTP SERVICE adapter.
///
/// In the integration test we do NOT replace this class; instead we start
/// a REAL HTTP server with WireMock.Net and point the BaseAddress at it.
/// That way serialization, headers, status codes and timeout behaviour
/// stay inside the test scope.
/// </summary>
public sealed class HttpCurrencyClient(HttpClient httpClient) : ICurrencyClient
{
public async Task<decimal> GetTryRateAsync(string currency, CancellationToken cancellationToken = default)
{
using var response = await httpClient.GetAsync($"rates/{currency}", cancellationToken);

if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
{
throw new KeyNotFoundException($"'{currency}' için kur bulunamadı.");
}

response.EnsureSuccessStatusCode();

var payload = await response.Content.ReadFromJsonAsync<RateResponse>(cancellationToken);

return payload?.Rate ?? throw new InvalidOperationException("Kur yanıtı boş geldi.");
}
}

The endpoint turns the client's exceptions into HTTP status codes. An unknown currency becomes 400. Any other HTTP failure becomes 502 Bad Gateway, which tells the caller that a dependency failed, not the API itself.

M09.IntegrationApi/Endpoints/BookEndpoints.cs

catch (KeyNotFoundException)
{
return TypedResults.Problem($"'{currency}' para birimi desteklenmiyor.", statusCode: 400);
}
catch (HttpRequestException)
{
// Returning 502 when the external service fails is a CONTRACT and must be tested.
return TypedResults.Problem("Kur servisine ulaşılamıyor.", statusCode: 502);
}

Why not mock ICurrencyClient instead? A mock would skip everything inside HttpCurrencyClient: the relative URL rates/{currency}, the 404 check, EnsureSuccessStatusCode, and JSON parsing into RateResponse. A bug in any of those would never show up. Faking the HttpMessageHandler is closer, but you would hand-write every response and still skip the real socket and the client's timeout. With WireMock.Net the whole HttpClient stack runs against a real server, and the only thing you control is what that server answers.

Wiring WireMock.Net into the Factory

BooksApiFactory starts a WireMock server once and overrides the base address in configuration. Program.cs reads Currency:BaseAddress when it registers the typed client, so the application sends its requests to WireMock without any code change.

M09.IntegrationApi.Tests/Infrastructure/BooksApiFactory.cs

public Task InitializeAsync()
{
// Start a real HTTP server on a random port.
CurrencyServer = WireMockServer.Start();
return Task.CompletedTask;
}

// inside ConfigureWebHost:
builder.ConfigureAppConfiguration((_, config) =>
{
// Point the external service address at the WireMock server.
config.AddInMemoryCollection(new Dictionary<string, string?>
{
["Currency:BaseAddress"] = CurrencyServer.Url,
});
});

WireMockServer.Start() with no arguments picks a free port, so parallel CI jobs do not collide.

Pitfall: Reset the Server Before Every Test

The WireMock server is shared by every test in the collection. Rules (called mappings) and the request log stay on the server until you remove them. If a test does not clean up, the next test can match a rule it never set up, or see requests it never sent. The test class resets the server at the start of each test:

M09.IntegrationApi.Tests/ExternalApiTests.cs

public async Task InitializeAsync()
{
await factory.ResetDatabaseAsync();
factory.CurrencyServer.Reset(); // Do not let the previous test's rules leak!

await factory.SeedAsync(new Book
{
Isbn = "978-KUR-001", Title = "Fiyatlı Kitap", Author = "Yazar",
PriceTry = 400m, PublishedYear = 2024,
});

await using var db = factory.CreateDbContext();
_bookId = db.Books.Single(b => b.Isbn == "978-KUR-001").Id;

_client = factory.CreateClient();
}

Reset() clears both the mappings and the log entries.

Success, Error Mapping and Outgoing Requests

Each test programs only the response it needs, using Given(...) for the request matcher and RespondWith(...) for the response.

M09.IntegrationApi.Tests/ExternalApiTests.cs

[Fact]
public async Task PriceInCurrency_UsesRateFromExternalService()
{
// Arrange — program the external service's response.
factory.CurrencyServer
.Given(Request.Create().WithPath("/rates/USD").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody("""{"currency":"USD","rate":40.0}"""));

// Act
var result = await _client.GetFromJsonAsync<PriceInCurrencyResponse>(
$"/api/books/{_bookId}/price/USD");

// Assert — 400 TL / 40 = 10 USD
result!.Price.Should().Be(10m);
result.Currency.Should().Be("USD");
}

[Fact]
public async Task PriceInCurrency_WhenExternalServiceFails_Returns502()
{
// ERROR INJECTION: the external service returns 500.
// Turning that into 502 is OUR CONTRACT.
factory.CurrencyServer
.Given(Request.Create().WithPath("/rates/EUR").UsingGet())
.RespondWith(Response.Create().WithStatusCode(500));

var response = await _client.GetAsync($"/api/books/{_bookId}/price/EUR");

response.StatusCode.Should().Be(HttpStatusCode.BadGateway);
}

[Fact]
public async Task PriceInCurrency_SendsExpectedRequestToExternalService()
{
factory.CurrencyServer
.Given(Request.Create().WithPath("/rates/GBP").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody("""{"currency":"GBP","rate":50.0}"""));

await _client.GetAsync($"/api/books/{_bookId}/price/GBP");

// WireMock RECORDS incoming requests → we can verify the outgoing request.
var log = factory.CurrencyServer.LogEntries.Should().ContainSingle().Subject;
log.RequestMessage!.Path.Should().Be("/rates/GBP");
log.RequestMessage!.Method.Should().Be("GET");
}

The first test proves the whole chain: the URL the client builds, the JSON it parses, and the calculation in the endpoint. The second proves the error contract with a real 500 response, so EnsureSuccessStatusCode really throws. A sibling test does the same for 404 and expects 400. The third looks at the other direction: LogEntries shows exactly what the application sent, which is how you catch a wrong path, a missing header or an extra call.

Latency and Stateful Scenarios

WireMock.Net can also delay a response and change its behaviour across calls.

M09.IntegrationApi.Tests/ExternalApiTests.cs

[Fact]
public async Task PriceInCurrency_WithSimulatedLatency_StillCompletes()
{
// LATENCY INJECTION: slow service scenario.
// To test timeout behaviour, raise the delay above the timeout.
factory.CurrencyServer
.Given(Request.Create().WithPath("/rates/CHF").UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody("""{"currency":"CHF","rate":50.0}""")
.WithDelay(TimeSpan.FromMilliseconds(200)));

var result = await _client.GetFromJsonAsync<PriceInCurrencyResponse>(
$"/api/books/{_bookId}/price/CHF");

result!.Price.Should().Be(8m);
}

[Fact]
public async Task ExternalService_CanModelStatefulScenarios()
{
// SCENARIO STATE: when the ORDER of interactions matters.
// First call 500, second call 200 → you can test retry logic.
const string scenario = "GeciciHata";

factory.CurrencyServer
.Given(Request.Create().WithPath("/rates/SEK").UsingGet())
.InScenario(scenario)
.WillSetStateTo("IlkDenemeYapildi")
.RespondWith(Response.Create().WithStatusCode(500));

factory.CurrencyServer
.Given(Request.Create().WithPath("/rates/SEK").UsingGet())
.InScenario(scenario)
.WhenStateIs("IlkDenemeYapildi")
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody("""{"currency":"SEK","rate":4.0}"""));

var first = await _client.GetAsync($"/api/books/{_bookId}/price/SEK");
var second = await _client.GetFromJsonAsync<PriceInCurrencyResponse>(
$"/api/books/{_bookId}/price/SEK");

first.StatusCode.Should().Be(HttpStatusCode.BadGateway);
second!.Price.Should().Be(100m);
}

The delay test shows the request still completes when the service is slow. Raise the delay above HttpClient.Timeout (10 seconds in this API) and you can test timeout handling the same way. Such a test would reveal a real gap: a timeout throws TaskCanceledException, not HttpRequestException, so the endpoint would not map it to 502. The scenario test models a transient failure: the first call gets a 500 and moves the scenario to a new state, the second call matches the rule for that state and gets a 200. The API has no retry policy today, so the test sends two requests itself. If you add a retry handler later, the same mappings prove that one request now succeeds.

Summary

  1. WireMock.Net runs a real HTTP server in process, so the real HttpClient code, serialization and status handling are tested.
  2. Point the application at it through configuration; production code does not change.
  3. Call Reset() at the start of each test, or mappings and log entries leak between tests.
  4. Test error mapping (404 to 400, 500 to 502) with real error responses, and inspect LogEntries to verify outgoing requests.
  5. Use WithDelay for latency and InScenario/WhenStateIs for multi-step behaviour such as retries.