Lesson 44 of 93 · 6 min read · Updated
Faking HttpClient in Unit Tests with a Stub HttpMessageHandler
On this page
Classes that call HTTP APIs are common, and testing them raises a question: what do you fake? Mocking HttpClient itself does not work well, because convenience methods such as GetAsync are not virtual and its behavior is complex. The right boundary is HttpMessageHandler, the object that HttpClient hands every request to. This lesson builds a small stub handler and uses it to test a weather client: JSON deserialization, request URI building, error status codes and network failures.
Technical Requirements
- .NET 11 SDK
- xUnit 2.9.3
- FluentAssertions 7.2.2
- No mocking library and no network: the stub handler is plain C#
The Class Under Test
WeatherClient takes an HttpClient through its constructor. It never creates one itself, which is what makes it testable.
M05.TestableDesign/Ports/IWeatherClient.cs
Four behaviors are worth testing here: the relative URI with an escaped city name, the call to EnsureSuccessStatusCode, JSON deserialization into WeatherSnapshot, and the handling of transport errors. If you replaced HttpClient with an interface and mocked it, you would skip all four. The test would check that your code calls a mock, not that it talks HTTP correctly.
In production you would register the client with AddHttpClient<WeatherClient>(...) and set the base address there. The factory then creates the HttpClient with a pooled handler chain. In a test you skip the factory and build the HttpClient by hand around a stub. The WeatherClient code is the same in both cases.
A Stub Handler That Also Records Requests
HttpMessageHandler has one abstract method, SendAsync. Override it, and you control everything HttpClient receives.
M05.TestableDesign.Tests/Doubles/StubHttpMessageHandler.cs
The handler takes a responder function, so each test decides what to return. It stores every request in Requests, which makes it a spy as well as a stub. The static Json helper covers the most common case: a fixed status code with a JSON body. The handler also honors cancellation, like a real handler would.
Because the stub sits under HttpClient, everything above it is real. The client pipeline combines BaseAddress with the relative path, EnsureSuccessStatusCode inspects the real status code, and System.Text.Json reads the real response stream. The only fake part is the network.
Testing the Happy Path and the Request
Each test builds a real HttpClient around the stub and sets a BaseAddress, just as the application would through IHttpClientFactory.
M05.TestableDesign.Tests/HttpBoundaryTests.cs
The first test runs the real JSON deserializer. The camelCase JSON maps to the PascalCase record because ReadFromJsonAsync uses web defaults, which are case-insensitive. The second test checks what went over the wire: the method and the full URI, including the base address.
Pitfall: Uri.ToString() Decodes the URI
The comment in the second test points at a trap. Uri.ToString() returns a display form in which escaped characters such as %20 are turned back into spaces. An assertion on ToString() would pass even if the code forgot Uri.EscapeDataString. AbsoluteUri keeps the escaped form, so the test sees %C4%B0 for the Turkish capital dotted I and %20 for the space. Use AbsoluteUri whenever encoding matters.
Error Status Codes and Network Failures
The same stub returns a 500, or throws as a broken network would.
M05.TestableDesign.Tests/HttpBoundaryTests.cs
The 500 test proves that EnsureSuccessStatusCode is really called: without it, the client would deserialize {} and return an empty snapshot instead of failing. The second test makes the handler throw, which is what a dropped connection looks like to HttpClient. The message "Bağlantı koptu" means "connection lost".
The stub is enough for one or two canned responses. When tests need request matching, stateful scenarios or delays, an in-process fake server such as WireMock.Net is the next step.
Summary
- Do not mock
HttpClient; fakeHttpMessageHandler, which receives every requestHttpClientsends. - Inject
HttpClientinto the class so a test can pass one built around a stub handler. - Recording requests turns the stub into a spy, so you can assert on method and URI.
- Assert on
RequestUri.AbsoluteUri, notToString(), becauseToString()decodes escaped characters. - The same handler can return error status codes or throw, so failure paths are tested with no network.