📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

Your service calls a third-party HTTP API. How do you use WireMock.Net to test it, including the API being slow, returning errors or sending malformed responses? Show how you wire it into the app under test and verify what was sent.

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.

Mid-Level Coding Intermediate aspnet-core http-client integration-testing resilience testing wiremock-net

🎯 Key points

  • WireMock.Net starts a real HTTP server on a random port; the app's HttpClient calls it over the network stack
  • Given(Request.Create()...).RespondWith(Response.Create()...) for matching and responses; keep stub bodies in JSON files copied from the provider
  • WithDelay for slow responses, WithStatusCode(503/429) and WithFault for malformed or empty responses
  • InScenario / WhenStateIs / WillSetStateTo for deterministic retry sequences (fail, then succeed)
  • Point the typed client's base address at server.Url via configuration in WebApplicationFactory; shrink resilience timeouts in tests
  • Verify outbound requests with server.LogEntries: count, headers (API key, Idempotency-Key) and body
  • server.Reset() between tests; exercises the real HttpClient pipeline and resilience handler, unlike mocking the client

⏱ 30-second answer

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:

  • Slow: .WithDelay(TimeSpan.FromSeconds(5)) to prove timeouts fire.
  • Errors: 503 or 429 with Retry-After, and stateful scenarios (fail, fail, succeed) to test retries.
  • Broken: .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.

🗣 Full answer (senior)

How I would answer this in an interview

"For outbound HTTP I don't mock HttpClient or 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 at server.Url through 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 WithDelay and 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 read server.LogEntries to 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."


WireMock.Net building blocks

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()

Which failure tests to write

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)

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate tests outbound integrations realistically, including failure modes and resilience behaviour.

Green flags

  • Prefers a real stub server over mocking HttpClient for integration tests
  • Tests delays, 5xx, 429 and malformed responses
  • Verifies outbound requests (count, headers, idempotency keys)
  • Makes timeouts configurable so tests stay fast

Red flags

  • Only tests the happy path
  • Mocks HttpClient with complex handler setups for integration tests
  • Unaware of the default 100-second HttpClient timeout or of retrying unsafe POSTs

📚 Learn in depth

1. Why a real server beats mocking HttpClient

 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.

2. How matching works

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.

3. Delays and faults

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.

4. Stateful scenarios

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.

5. Resilience pipelines under test

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.

6. In-process versus container

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.

Try it yourself

  1. Stub a GET, call it with a typed client and assert the deserialised result.
  2. Add WithDelay(5s) and an attempt timeout of 1 s; assert a TimeoutRejectedException or your fallback.
  3. Build a three-step scenario (503, 503, 200) and assert the request count is 3.
  4. Return FaultType.EMPTY_RESPONSE and see which exception your code gets.
  5. Assert from LogEntries that every POST carried an Idempotency-Key header.

💻 Code

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
    }
}

⚠ Common mistakes

  • Mistake: Mocking the typed client interface in integration tests. Why it is wrong: Serialisation, headers, handlers and resilience policies never run. Instead: Use WireMock.Net so the real HttpClient pipeline executes.
  • Mistake: Hard-coding a port for the stub server. Why it is wrong: Parallel test classes and CI agents collide. Instead: WireMockServer.Start() with a random port and pass server.Url through configuration.
  • Mistake: Testing timeouts with production values. Why it is wrong: A retry test with 10-second timeouts and back-off takes a minute. Instead: Make timeouts configurable and shrink them in the test factory.
  • Mistake: Not resetting mappings and logs between tests. Why it is wrong: Stubs and request counts from earlier tests leak into assertions. Instead: Call Reset() in the test constructor or use a server per class.
  • Mistake: Only testing the happy path. Why it is wrong: Production incidents come from slow, rate-limited and broken responses. Instead: Add 503, 429, timeout, malformed body and 400 tests.
  • Mistake: Retrying POSTs without idempotency. Why it is wrong: A timeout after the provider processed the request causes duplicate charges or orders. Instead: Send an idempotency key and verify from LogEntries, or disable retries for unsafe methods.
  • Mistake: Inventing stub payloads by hand. Why it is wrong: They drift from the real API and tests pass against a fiction. Instead: Copy responses from the provider's sandbox or docs into JSON files and back them with a contract or sandbox smoke test.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate talks about testing slow or failing dependencies. Why: Checks the wider approach to testing third-party failure modes.
    How to answer

    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.

  2. When: Candidate mentions AddStandardResilienceHandler or Polly. Why: Checks understanding of the resilience pipeline itself.
    How to answer

    Add Microsoft.Extensions.Http.Resilience and call AddStandardResilienceHandler() on the HttpClient registration. It builds a Polly v8 pipeline. From outside in:

    • a rate limiter,
    • a total timeout (30 s),
    • a retry (3 retries, exponential back-off with jitter from 2 s, honours Retry-After),
    • a circuit breaker (opens at a 10% failure ratio over 30 s, once there have been at least 100 requests, for 5 s),
    • an attempt timeout (10 s) for each try.

    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.

🛠 Real-world problems: how you handle them

Freight provider outage exhausted request threads
Situation
A quoting API on [Azure Container Apps] calling a freight-rate provider for every quote, [~50 requests per second] at peak during [end-of-month].
Signals
Provider degraded to [20-30 s] responses; our P99 latency jumped from [400 ms] to over 60 s, Application Insights showed dependency calls stuck, the gateway returned 504s, and other endpoints slowed as connections and threads were held.
Investigation
Application Insights dependency telemetry showed calls lasting until the HttpClient default 100-second timeout. The code had no attempt timeout and no fallback. Reproduced it locally with WireMock.Net WithDelay(30s) behind WebApplicationFactory, and a small k6 run showed the same pile-up.
Resolution
Immediately set HttpClient.Timeout to [5 s] and deployed. Then added AddStandardResilienceHandler with a [2 s] attempt timeout, a circuit breaker and a cached last-known rate as fallback, with WireMock.Net tests for delay, 503 sequences and malformed bodies.
Prevention
Every new outbound integration needs the WireMock failure matrix before merge; alerts on dependency duration P95; a quarterly game day injecting provider latency in staging.

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.

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me