In an ASP.NET Core 10 unit test, how do you stub HttpClient responses for a grocery app's loyalty-points client without calling the real API?
answer
- the seam under HttpClient
- override protected SendAsync
- new HttpClient(handler) { BaseAddress }
- GetAsync is not virtual
- Protected().Setup with ItExpr
basics
~20 sGive the client an HttpClient built on a stub HttpMessageHandler whose SendAsync returns canned responses. HttpClient's GetAsync and PostAsync are not virtual, so mocking HttpClient itself fails; the handler is the seam every request passes through.
solid answer
~40 s`HttpClient` funnels every `GetAsync`, `PostAsJsonAsync` or `SendAsync` call into its `HttpMessageHandler`'s `protected abstract SendAsync(HttpRequestMessage, CancellationToken)`. A test therefore writes a small `StubHttpMessageHandler : HttpMessageHandler` that records each request and returns a prepared `HttpResponseMessage`, for example `new(HttpStatusCode.OK) { Content = JsonContent.Create(points) }`, and constructs `new HttpClient(stub) { BaseAddress = new Uri("https://loyalty.test/") }` for the client under test. The test then asserts on the result and on the captured method, URI, headers and body. Error paths are just other responses: a 503, an `HttpRequestException` thrown from the stub, or a `TaskCanceledException`. Mocking `HttpClient` with Moq fails because its convenience methods are non-virtual; mocking the handler works through `Protected().Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())`, a string-based setup that refactoring tools cannot follow.
code
csharp · 12 linespublic sealed class StubHttpMessageHandler(Func<HttpRequestMessage, HttpResponseMessage> respond)
: HttpMessageHandler
{
public List<HttpRequestMessage> Requests { get; } = [];
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Requests.Add(request);
return Task.FromResult(respond(request));
}
}go deeper
Remember that HttpClient is tested by giving it a fake HttpMessageHandler, not by mocking HttpClient itself.
Write the stub handler, explain why GetAsync cannot be mocked, and show what the test asserts about the outgoing request.
Cover failure mapping, request-count checks and base-address bugs, and keep factory and resilience behaviour for tests of the configured pipeline.
Standardise one stub-handler helper across services so outbound-call tests stay consistent and cheap, and decide where contract tests take over.
## Why the handler is the seam `HttpClient` derives from `HttpMessageInvoker`. Its convenience methods, `GetAsync`, `PostAsync`, `GetStringAsync`, and the `System.Net.Http.Json` extensions such as `GetFromJsonAsync`, all build an `HttpRequestMessage` and end up in the **handler's** `SendAsync`. In production that handler is a socket-based pipeline; in a unit test it can be anything that derives from `HttpMessageHandler`. Mocking `HttpClient` directly does not work with proxy-based libraries: `GetAsync` and its siblings are **non-virtual**, so Moq throws `NotSupportedException`, and the JSON helpers are extension methods. ## A hand-written stub The grocery app's `LoyaltyClient` calls `GET points/{customerId}` on a loyalty service and maps the JSON into a balance. A reusable stub needs only a few lines: 1. Derive from `HttpMessageHandler`. 2. Override `protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)`. 3. Record what arrived, reading the body inside `SendAsync` if the test needs it. 4. Return the response the test prepared, or invoke a delegate so each test decides. The client under test receives `new HttpClient(stub) { BaseAddress = new Uri("https://loyalty.test/") }` through its constructor, exactly as a typed client would receive one from the factory in production. ## What to assert | Concern | Assert on | |---|---| | request shape | `request.Method`, `request.RequestUri`, headers such as `Authorization` | | request body | the string or object read from `request.Content` inside the stub | | success mapping | the value the client returned for a 200 with `JsonContent.Create(...)` | | failure mapping | behaviour for 404, 503, a thrown `HttpRequestException` or a cancellation | | call count | how many requests the stub received, which exposes accidental retries or loops | ## Asserting the body the client sent For `POST` and `PUT` calls the request body is part of the contract: - Read it **inside** the stub, for example `await request.Content!.ReadAsStringAsync(cancellationToken)` or `ReadFromJsonAsync<T>()`, and store the result; the caller may dispose the request after the call returns. - Assert on deserialised values rather than on the raw JSON string, so property order and whitespace do not break the test. - Check `request.Content.Headers.ContentType` when the API cares about `application/json` versus form encoding. ## Timeouts and cancellation A stub can model slow or failed transport too: throw `HttpRequestException` to simulate a refused connection, or throw `TaskCanceledException` to simulate a timeout, then assert that the client maps each to its own failure result instead of letting the exception escape to the endpoint. ## The Moq alternative Moq can mock the abstract handler, but `SendAsync` is protected, so the setup is string-based: - `handler.Protected().Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>()).ReturnsAsync(response)`. - Use `ItExpr`, not `It`: outside an expression tree `It.IsAny<T>()` evaluates to `default` and the setup would match only null arguments. - Verification uses `Protected().Verify("SendAsync", Times.Once(), ...)`. The method name is a string, so a typo fails at run time and refactoring tools cannot follow it. Many teams therefore prefer the ten-line hand-written stub, which also reads better in a failure message. ## Gotchas - **Base address slashes.** Relative URIs combine with `BaseAddress` by URI rules: with `https://loyalty.test/api` (no trailing slash) a request for `points/42` goes to `https://loyalty.test/points/42`. Give the base address a trailing slash; the test will catch the production bug if the stub asserts on `RequestUri`. - **Response reuse.** Client code usually disposes each `HttpResponseMessage` it receives, so a stub that hands the same instance to a second request returns a disposed object; create a new response per call. - **Disposal.** A test-owned `HttpClient` disposes its handler by default; that is fine for a per-test stub. - **Scope.** This tests the client class alone. Registration through `AddHttpClient`, `DelegatingHandler` pipelines and resilience handlers belong to tests of the configured factory, not to this stub. ## Why not a real HTTP server in a unit test Starting a listener for each test adds ports, timing and cleanup for no extra assurance about the client's own logic. The stub keeps the test in memory and deterministic; the real wire protocol belongs in integration or contract tests.
- How would you test that LoyaltyClient turns a 503 into a domain-specific failure?Have the stub return `new HttpResponseMessage(HttpStatusCode.ServiceUnavailable)` and assert the client's result or exception. If the client calls `EnsureSuccessStatusCode()`, the raw failure is an `HttpRequestException` carrying the status code, which the client should translate.
- Why is new Mock<HttpClient>().Setup(c => c.GetAsync(...)) a dead end?`GetAsync` is a non-virtual instance method, so Moq's proxy cannot override it and throws `NotSupportedException` at setup. The JSON helpers are extension methods and fail the same way. Stub the handler underneath instead.
- Mock HttpClient.GetAsync with Moq; it is virtual like SendAsync.
- Point unit tests at the real loyalty API with a test account.
- It.IsAny<T>() works inside a Moq Protected() string-based setup.
- BaseAddress without a trailing slash still keeps its last path segment.
- One HttpResponseMessage instance can safely answer every request a client makes.