Most .NET applications communicate with external services through HTTP APIs, databases, message brokers, and other network-dependent systems. During development, these services usually respond quickly and consistently. However, production environments are different. Network connections can fail, responses can become slow, external services can return errors, and requests can time out unexpectedly.

An application that works correctly when every dependency is available may behave very differently when one service becomes unreliable. It might retry requests too frequently, block incoming traffic, return incomplete data, or leave operations in an inconsistent state.

Testing these situations is important because network failures are not unusual exceptions in distributed applications. They are conditions that developers should expect and handle.

.NET provides several ways to simulate network problems without depending on an actual failing server. One useful approach is to create custom HTTP message handlers that return errors, introduce delays, or simulate timeouts. These handlers can be used with HttpClient in unit and integration tests.

In this article, we will explore how to simulate realistic network failures in .NET applications and test whether application code handles them correctly.

Why Network Failure Testing Matters

Consider an ASP.NET Core application that calls an external payment service. Under normal conditions, the service responds within a few hundred milliseconds. The application processes the response and completes the transaction.

Now consider a few production scenarios:

  • The payment service returns HTTP 503 because it is temporarily unavailable.

  • The network connection fails before the request reaches the server.

  • The external service takes longer than the configured timeout.

  • The server returns HTTP 200 but provides invalid JSON.

  • The user cancels the request while the application is waiting for a response.

Each situation requires different handling.

For example, retrying a temporary 503 response may be reasonable, but retrying a request after the user cancels it is usually unnecessary. Similarly, a connection failure might justify another attempt, while an invalid response may indicate a contract problem that needs investigation.

Testing only successful responses does not reveal these problems. A reliable test suite should cover both expected responses and failure conditions.

Creating a Custom HTTP Message Handler

HttpClient uses an HttpMessageHandler to send HTTP requests and receive responses. This makes it possible to replace the real network communication with a controlled implementation during testing.

A custom handler can inspect an outgoing request and decide what response to return.

Create a class named SimulatedNetworkHandler:

C#
using System.Net;
using System.Net.Http;

public class SimulatedNetworkHandler : HttpMessageHandler
{
    private readonly Func<
        HttpRequestMessage,
        CancellationToken,
        Task<HttpResponseMessage>> _responseFactory;

    public SimulatedNetworkHandler(
        Func<
            HttpRequestMessage,
            CancellationToken,
            Task<HttpResponseMessage>> responseFactory)
    {
        _responseFactory = responseFactory;
    }

    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        return _responseFactory(
            request,
            cancellationToken);
    }
}

The handler accepts a function that receives the outgoing request and returns an HTTP response.

This design allows each test to control the behavior of the external service without starting a real web server.

For example, a test can return HTTP 200 for one request, HTTP 503 for another, or introduce a delay before returning a response.

Simulating an HTTP 503 Service Unavailable Response

A temporary service failure is one of the most common problems in distributed applications.

An external API may return HTTP 503 when it cannot process requests because of maintenance, temporary resource exhaustion, or another availability problem.

The following example creates a handler that always returns HTTP 503.

C#
using System.Net;

var handler = new SimulatedNetworkHandler(
    (request, cancellationToken) =>
    {
        var response = new HttpResponseMessage(
            HttpStatusCode.ServiceUnavailable)
        {
            Content = new StringContent(
                "Service temporarily unavailable")
        };

        return Task.FromResult(response);
    });

using var httpClient = new HttpClient(handler);

var response = await httpClient.GetAsync(
    "https://api.example.com/orders");

Console.WriteLine(
    $"Status: {(int)response.StatusCode}");

The application receives a normal HTTP response with status code 503. This is different from a connection failure because the request successfully reached an HTTP endpoint and received a response.

This distinction matters when implementing retry logic. Some HTTP errors may be temporary, while others indicate permanent problems such as invalid requests or missing permissions.

Simulating a Network Connection Failure

A connection failure occurs when the application cannot establish or maintain communication with the remote endpoint.

In a real application, HttpClient commonly reports these situations through HttpRequestException.

A custom handler can simulate this behavior by throwing the exception.

JavaScript
var handler = new SimulatedNetworkHandler(
    (request, cancellationToken) =>
    {
        throw new HttpRequestException(
            "Unable to establish a connection.");
    });

using var httpClient = new HttpClient(handler);

try
{
    await httpClient.GetAsync(
        "https://api.example.com/orders");
}
catch (HttpRequestException exception)
{
    Console.WriteLine(
        $"Network error: {exception.Message}");
}

This test verifies whether the application handles connection-related exceptions instead of allowing them to terminate the entire operation unexpectedly.

However, a custom message handler does not reproduce every detail of a real TCP connection failure. It simulates the exception observed by application code. It does not test DNS resolution, TLS negotiation, socket exhaustion, or operating-system networking behavior.

For those scenarios, additional integration tests using a real network environment may be necessary.

Simulating Slow Responses and Network Delays

Slow responses can be more difficult to detect than immediate failures. An external service might eventually return the correct result, but the delay can cause requests to remain active for too long.

This can increase resource usage and affect the responsiveness of the application.

The following handler introduces a delay before returning a successful response.

JavaScript
var handler = new SimulatedNetworkHandler(
    async (request, cancellationToken) =>
    {
        await Task.Delay(
            TimeSpan.FromSeconds(5),
            cancellationToken);

        return new HttpResponseMessage(
            HttpStatusCode.OK)
        {
            Content = new StringContent(
                """{"status":"success"}""")
        };
    });

using var httpClient = new HttpClient(handler);

var stopwatch = System.Diagnostics.Stopwatch.StartNew();

var response = await httpClient.GetAsync(
    "https://api.example.com/orders");

stopwatch.Stop();

Console.WriteLine(
    $"Elapsed: {stopwatch.ElapsedMilliseconds} ms");

The handler waits five seconds before returning the response.

This allows developers to verify whether the application remains responsive when an external dependency is slow.

It is particularly useful for testing API clients that call multiple external services. If several dependencies respond slowly, the application may experience longer response times even when none of the services has completely failed.

Testing Request Timeouts

A timeout defines how long an application is willing to wait for a response.

HttpClient supports a Timeout property that limits the duration of an HTTP operation. Developers can also use CancellationToken to control individual requests.

The following example configures a short timeout while the simulated service takes longer to respond.

C#
using System.Net;

var handler = new SimulatedNetworkHandler(
    async (request, cancellationToken) =>
    {
        await Task.Delay(
            TimeSpan.FromSeconds(5),
            cancellationToken);

        return new HttpResponseMessage(
            HttpStatusCode.OK);
    });

using var httpClient = new HttpClient(handler)
{
    Timeout = TimeSpan.FromSeconds(1)
};

try
{
    await httpClient.GetAsync(
        "https://api.example.com/orders");
}
catch (OperationCanceledException)
{
    Console.WriteLine(
        "The HTTP request was canceled or timed out.");
}

The request is canceled because the simulated response takes longer than the configured timeout.

An important detail is that HttpClient timeout exceptions can appear as OperationCanceledException or TaskCanceledException. These exception types can also occur when an application explicitly cancels a request.

For production code, distinguish between a timeout and an intentional cancellation when possible. A caller cancellation should generally stop the operation without triggering additional retries.

Building a Reusable API Client

Testing individual HTTP requests is useful, but most applications call external services through a dedicated API client.

Consider the following service that retrieves an order from an external API.

C#
using System.Net.Http.Json;

public class OrderApiClient
{
    private readonly HttpClient _httpClient;

    public OrderApiClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<Order?> GetOrderAsync(
        int orderId,
        CancellationToken cancellationToken = default)
    {
        var response = await _httpClient.GetAsync(
            $"orders/{orderId}",
            cancellationToken);

        response.EnsureSuccessStatusCode();

        return await response.Content.ReadFromJsonAsync<Order>(
            cancellationToken: cancellationToken);
    }
}

public class Order
{
    public int Id { get; set; }

    public string? Status { get; set; }
}

The client uses HttpClient to retrieve an order and converts the response into an Order object.

Because HttpClient is injected through the constructor, the service can be tested using a custom message handler.

This avoids making real API calls during unit tests.

Writing a Test for a Failed External Request

The following example uses xUnit to verify how OrderApiClient behaves when the external API returns HTTP 503.

C#
using System.Net;
using Xunit;

public class OrderApiClientTests
{
    [Fact]
    public async Task GetOrderAsync_ThrowsWhenServiceIsUnavailable()
    {
        var handler = new SimulatedNetworkHandler(
            (request, cancellationToken) =>
            {
                var response = new HttpResponseMessage(
                    HttpStatusCode.ServiceUnavailable);

                return Task.FromResult(response);
            });

        using var httpClient = new HttpClient(handler)
        {
            BaseAddress = new Uri(
                "https://api.example.com/")
        };

        var client = new OrderApiClient(httpClient);

        await Assert.ThrowsAsync<HttpRequestException>(
            () => client.GetOrderAsync(101));
    }
}

The test verifies that the API client does not treat a failed HTTP response as a successful operation.

The call to EnsureSuccessStatusCode throws an HttpRequestException when the response contains an unsuccessful status code.

This is a useful test because it checks the behavior of the actual application service rather than testing the custom handler in isolation.

Testing Cancellation Correctly

Cancellation is another important condition when working with external services.

For example, an ASP.NET Core request may be canceled because the client disconnects. If the application is still waiting for an external API, it should pass the cancellation token to HttpClient so the operation can stop.

A test can verify this behavior using a cancellation token.

C#
[Fact]
public async Task GetOrderAsync_StopsWhenCanceled()
{
    var handler = new SimulatedNetworkHandler(
        async (request, cancellationToken) =>
        {
            await Task.Delay(
                TimeSpan.FromSeconds(10),
                cancellationToken);

            return new HttpResponseMessage(
                HttpStatusCode.OK);
        });

    using var httpClient = new HttpClient(handler)
    {
        BaseAddress = new Uri(
            "https://api.example.com/")
    };

    var client = new OrderApiClient(httpClient);

    using var cancellationSource =
        new CancellationTokenSource(
            TimeSpan.FromMilliseconds(100));

    await Assert.ThrowsAnyAsync<OperationCanceledException>(
        () => client.GetOrderAsync(
            101,
            cancellationSource.Token));
}

The cancellation token is passed through the API client to HttpClient and then to the simulated handler.

When the token is canceled, the delay is interrupted and the operation stops.

This test helps identify a common problem: accepting a cancellation token in a method but failing to pass it to the underlying asynchronous operations.

Testing Retry Behavior

Some applications retry requests when an external service returns a temporary failure.

For example, a payment service might return HTTP 503 during a short maintenance period. A retry policy can attempt the operation again after a delay.

When testing retry behavior, it is important to verify more than whether the request eventually succeeds. The test should also confirm the number of attempts and ensure that retries stop after the configured limit.

A simulated handler can return an error on the first request and success on the next request.

C#
using System.Net;

var attempts = 0;

var handler = new SimulatedNetworkHandler(
    (request, cancellationToken) =>
    {
        attempts++;

        var statusCode = attempts < 2
            ? HttpStatusCode.ServiceUnavailable
            : HttpStatusCode.OK;

        return Task.FromResult(
            new HttpResponseMessage(statusCode));
    });

using var httpClient = new HttpClient(handler);

var response = await httpClient.GetAsync(
    "https://api.example.com/orders");

Console.WriteLine(
    $"Attempts: {attempts}");

Console.WriteLine(
    $"Final status: {response.StatusCode}");

This example demonstrates a service that fails once and then succeeds. It does not implement retry logic itself. It provides the controlled behavior needed to test a retry policy configured in the application.

When testing retries, remember that not every request is safe to repeat. A GET request is generally easier to retry than a payment submission or an order-creation request. For operations that change data, use idempotency keys or another mechanism that prevents duplicate processing.

Limitations of Simulated HTTP Handlers

Custom HttpMessageHandler implementations are useful because they are fast, predictable, and easy to configure. However, they do not reproduce every type of real network failure.

For example, they cannot fully validate:

  • DNS resolution failures.

  • TLS certificate errors.

  • TCP connection resets.

  • Proxy configuration problems.

  • Actual socket exhaustion.

  • Network packet loss and connection instability.

They also do not reproduce the behavior of a remote server that sends part of an HTTP response and then unexpectedly closes the connection.

For these situations, use integration tests with a real local HTTP server, a test proxy, or a controlled network environment. Tools such as Toxiproxy can introduce network conditions such as latency, connection interruptions, and bandwidth restrictions.

A good testing strategy combines fast handler-based tests with a smaller number of realistic network integration tests.

Best Practices for Network Failure Testing

Keep simulated handlers focused on one behavior. A handler that introduces delays, returns errors, and changes response content at the same time can make tests difficult to understand.

Use deterministic conditions instead of random failures in regular unit tests. Random network behavior can make a test pass on one run and fail on another, which makes debugging difficult.

Test cancellation separately from timeout behavior. Both can produce cancellation-related exceptions, but they represent different application conditions.

Also, verify the behavior of the complete API client. Testing only the HTTP handler does not prove that the application correctly handles exceptions, unsuccessful responses, or invalid response content.

Finally, test retry limits and avoid retrying non-idempotent operations without protection against duplicate processing.

Summary

Network failures are an expected part of distributed application development. Testing only successful HTTP responses leaves important application behavior unverified.

.NET's HttpMessageHandler provides a simple way to simulate HTTP errors, connection exceptions, slow responses, and cancellation without depending on an external service. These handlers can be combined with HttpClient and xUnit to test the behavior of real API client classes.

For more realistic scenarios involving DNS, TLS, sockets, or connection interruptions, use integration tests with a controlled network environment.

By combining unit tests and network-level integration tests, developers can identify failure-handling problems earlier and build .NET applications that behave more reliably when external services become unavailable.