Lesson 44 of 93 · 6 min read · Updated

Faking HttpClient in Unit Tests with a Stub HttpMessageHandler

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

  1. .NET 11 SDK
  2. xUnit 2.9.3
  3. FluentAssertions 7.2.2
  4. 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

using System.Net.Http.Json;

namespace M05.TestableDesign.Ports;

/// <summary>Weather response.</summary>
public sealed record WeatherSnapshot(string City, decimal TemperatureCelsius);

/// <summary>
/// Do NOT mock HttpClient ITSELF (not sealed, but its behavior is complex).
/// The right boundary is HttpMessageHandler: there you control the status code,
/// headers, body, delay and errors completely.
///
/// This class receives HttpClient from OUTSIDE, so a test can inject
/// an HttpClient with a fake handler.
/// </summary>
public sealed class WeatherClient(HttpClient httpClient)
{
public async Task<WeatherSnapshot> GetAsync(string city, CancellationToken cancellationToken = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(city);

// Building the URI is part of the behavior too; a test must be able to verify it.
using var response = await httpClient.GetAsync(
$"weather?city={Uri.EscapeDataString(city)}", cancellationToken);

response.EnsureSuccessStatusCode();

return await response.Content.ReadFromJsonAsync<WeatherSnapshot>(cancellationToken)
?? throw new InvalidOperationException("Hava durumu yanıtı boş geldi.");
}
}

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

using System.Net;

namespace M05.TestableDesign.Tests.Doubles;

/// <summary>
/// HttpMessageHandler is the real boundary BEHIND HttpClient.
/// By replacing it we fully control status code, headers, body, delay
/// and errors - without starting a real server.
///
/// When you need richer scenarios (request matching, scenario state, delay
/// injection), use WireMock.Net.
/// </summary>
public sealed class StubHttpMessageHandler(
Func<HttpRequestMessage, HttpResponseMessage> responder) : HttpMessageHandler
{
private readonly List<HttpRequestMessage> _requests = [];

/// <summary>Records incoming requests - in this respect it is also a SPY.</summary>
public IReadOnlyList<HttpRequestMessage> Requests => _requests;

protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
_requests.Add(request);
return Task.FromResult(responder(request));
}

/// <summary>Shortcut that returns a fixed JSON body.</summary>
public static StubHttpMessageHandler Json(HttpStatusCode statusCode, string json) =>
new(_ => new HttpResponseMessage(statusCode)
{
Content = new StringContent(json, System.Text.Encoding.UTF8, "application/json"),
});
}

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

private const string SuccessJson = """{"city":"Ankara","temperatureCelsius":21.5}""";

[Fact]
public async Task GetAsync_DeserializesSuccessfulResponse()
{
var handler = StubHttpMessageHandler.Json(HttpStatusCode.OK, SuccessJson);
using var httpClient = new HttpClient(handler) { BaseAddress = new Uri("https://hava.ornek/") };
var sut = new WeatherClient(httpClient);

var snapshot = await sut.GetAsync("Ankara");

snapshot.City.Should().Be("Ankara");
snapshot.TemperatureCelsius.Should().Be(21.5m);
}

[Fact]
public async Task GetAsync_BuildsExpectedRequestUri()
{
var handler = StubHttpMessageHandler.Json(HttpStatusCode.OK, SuccessJson);
using var httpClient = new HttpClient(handler) { BaseAddress = new Uri("https://hava.ornek/") };
var sut = new WeatherClient(httpClient);

await sut.GetAsync("İzmir Konak");

// URI building and escaping are part of the behavior:
// here we verify that the space and the Turkish character are encoded correctly.
var request = handler.Requests.Should().ContainSingle().Subject;
// CAREFUL: Uri.ToString() DECODES escaped characters.
// Use AbsoluteUri to see whether the encoding is correct.
request.RequestUri!.AbsoluteUri.Should().Be("https://hava.ornek/weather?city=%C4%B0zmir%20Konak");
request.Method.Should().Be(HttpMethod.Get);
}

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

[Fact]
public async Task GetAsync_WhenServerReturns500_Throws()
{
var handler = StubHttpMessageHandler.Json(HttpStatusCode.InternalServerError, "{}");
using var httpClient = new HttpClient(handler) { BaseAddress = new Uri("https://hava.ornek/") };
var sut = new WeatherClient(httpClient);

var act = () => sut.GetAsync("Ankara");

await act.Should().ThrowAsync<HttpRequestException>();
}

[Fact]
public async Task GetAsync_WhenHandlerFaults_PropagatesNetworkFailure()
{
// Network failure injection: the real boundary can do this, so we can test it.
var handler = new StubHttpMessageHandler(_ => throw new HttpRequestException("Bağlantı koptu"));
using var httpClient = new HttpClient(handler) { BaseAddress = new Uri("https://hava.ornek/") };
var sut = new WeatherClient(httpClient);

var act = () => sut.GetAsync("Ankara");

await act.Should().ThrowAsync<HttpRequestException>().WithMessage("Bağlantı koptu");
}

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

  1. Do not mock HttpClient; fake HttpMessageHandler, which receives every request HttpClient sends.
  2. Inject HttpClient into the class so a test can pass one built around a stub handler.
  3. Recording requests turns the stub into a spy, so you can assert on method and URI.
  4. Assert on RequestUri.AbsoluteUri, not ToString(), because ToString() decodes escaped characters.
  5. The same handler can return error status codes or throw, so failure paths are tested with no network.