LESSON 12 OF 18

12. Test Host Configuration and Replacing Application Dependencies

Configure a custom WebApplicationFactory, replace production services with test doubles, and build safe, deterministic ASP.NET Core integration tests.

45 dk 71

Introduction

In the previous lesson, we created our first API integration test with WebApplicationFactory. Starting the application, however, is only the beginning. In a real application, the test environment may need a different database, external service, messaging system, clock provider, or authentication component than production. The test host must therefore be customized in a controlled way.

In this lesson, we will create a custom WebApplicationFactory<TEntryPoint>. Through this factory, we will select a test environment, add test-specific configuration, and replace a production dependency with a test double. The HTTP pipeline will remain real, while external systems will be isolated so that tests stay fast, deterministic, and safe.

Why customize the test host?

WebApplicationFactory uses the application entry point to build a test server and dependency injection container. The default behavior is enough for simple tests, but custom configuration is useful when you need to:

  • Use a test database instead of the production database.
  • Replace payment, email, inventory, or messaging services with fakes.
  • Provide test-specific appsettings values.
  • Control authentication and authorization behavior.
  • Prevent tests from calling real third-party services.

The main principle is to keep real only the components that the test is intended to verify. For example, if we are testing an order endpoint’s HTTP pipeline, model binding, validation, and application flow, the test should not make a real network call to a payment provider. Instead, we can provide a test implementation that follows the same contract.

Defining an application contract

First, define the production dependency behind an interface. In this example, creating an order sends an authorization request to an external payment provider.

public interface IPaymentGateway {    Task<PaymentResult> AuthorizeAsync(        decimal amount,        CancellationToken cancellationToken = default); } public sealed record PaymentResult(bool IsApproved, string? TransactionId);

The production implementation may call the provider over HTTP:

public sealed class PaymentGateway : IPaymentGateway {    private readonly HttpClient _httpClient;    public PaymentGateway(HttpClient httpClient)    {        _httpClient = httpClient;    }    public async Task<PaymentResult> AuthorizeAsync(        decimal amount,        CancellationToken cancellationToken = default)    {        using var response = await _httpClient.PostAsJsonAsync(            "/payments/authorize",            new { amount },            cancellationToken);        response.EnsureSuccessStatusCode();        return await response.Content.ReadFromJsonAsync<PaymentResult>(            cancellationToken: cancellationToken)            ?? throw new InvalidOperationException("Payment response is empty.");    } }

Register it as a typed client in Program.cs:

builder.Services.AddHttpClient<IPaymentGateway, PaymentGateway>(    client =>    {        client.BaseAddress = new Uri(            builder.Configuration["Payment:BaseUrl"]!);    });

The application depends only on IPaymentGateway. This separation allows the test host to replace the production implementation without changing application code.

Creating a custom WebApplicationFactory

In the test project, create a CustomWebApplicationFactory. With the minimal hosting model, the application entry point is usually the Program class. To make it visible to the test project, add the following line at the end of the API project’s Program.cs file:

public partial class Program { }

Now add the factory:

using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; public sealed class CustomWebApplicationFactory    : WebApplicationFactory<Program> {    protected override void ConfigureWebHost(IWebHostBuilder builder)    {        builder.UseEnvironment("Testing");        builder.ConfigureAppConfiguration((context, configuration) =>        {            var testSettings = new Dictionary<string, string?>            {                ["Payment:BaseUrl"] = "https://test-payment.invalid",                ["Features:EnableDetailedErrors"] = "true"            };            configuration.AddInMemoryCollection(testSettings);        });        builder.ConfigureTestServices(services =>        {            services.RemoveAll<IPaymentGateway>();            services.AddScoped<IPaymentGateway, FakePaymentGateway>();        });    } }

UseEnvironment("Testing") makes the application run in the Testing environment. This also enables environment-specific files such as appsettings.Testing.json. AddInMemoryCollection provides test values with an explicit source that is convenient for integration tests.

Replacing production services

In the previous example, we explicitly removed the production registration before adding the fake. This is clearer and safer than depending on the order of registrations. If multiple registrations exist for the same service type, resolving a single service commonly uses the last registration, but tests should not rely on accidental registration order.

builder.ConfigureTestServices(services => {    services.RemoveAll<IPaymentGateway>();    services.AddScoped<IPaymentGateway, FakePaymentGateway>(); });

An alternative is to find a specific ServiceDescriptor and remove it:

builder.ConfigureServices(services => {    var descriptor = services.SingleOrDefault(        service => service.ServiceType == typeof(IPaymentGateway));    if (descriptor is not null)    {        services.Remove(descriptor);    }    services.AddScoped<IPaymentGateway, FakePaymentGateway>(); });

ConfigureTestServices communicates that the registration is intended for testing. Use it for test-oriented replacements applied by the factory. If only one test needs a different dependency, use WithWebHostBuilder so that the change is limited to that test.

Building a deterministic fake

The fake implementation should produce a payment result without contacting an external system. To vary behavior in individual tests, expose configurable properties:

public sealed class FakePaymentGateway : IPaymentGateway {    public bool IsApproved { get; set; } = true;    public string TransactionId { get; set; } = "test-transaction-001";    public int CallCount { get; private set; }    public Task<PaymentResult> AuthorizeAsync(        decimal amount,        CancellationToken cancellationToken = default)    {        CallCount++;        return Task.FromResult(            new PaymentResult(IsApproved, TransactionId));    } }

There is an important lifetime detail here. If a fake has mutable state such as CallCount, consider whether it should be scoped or singleton. A singleton fake may be easy to configure, but it can leak state between tests. A scoped fake has a shorter lifetime, but the test must resolve it from the correct scope. Avoid changing production lifetimes casually; evaluate thread safety and test isolation first.

Testing the API through the factory

Assume that the endpoint is POST /api/orders and returns 201 Created after a successful payment authorization.

public sealed class OrderApiTests    : IClassFixture<CustomWebApplicationFactory> {    private readonly HttpClient _client;    public OrderApiTests(CustomWebApplicationFactory factory)    {        _client = factory.CreateClient();    }    [Fact]    public async Task CreateOrder_WhenPaymentIsApproved_ReturnsCreated()    {        var request = new        {            customerId = "customer-001",            items = new[]            {                new { productId = "product-001", quantity = 2 }            }        };        using var response = await _client.PostAsJsonAsync(            "/api/orders", request);        response.StatusCode.Should().Be(HttpStatusCode.Created);    } }

This test runs the controller, routing, JSON serialization, validation, application service, and fake payment gateway together. Because the real payment network is not involved, the test remains fast and repeatable.

Replacing a dependency for one test

Not every test in a class needs the same fake behavior. To verify that a rejected payment produces 402 Payment Required, create a derived factory configuration for that test:

[Fact] public async Task CreateOrder_WhenPaymentIsRejected_ReturnsPaymentRequired() {    await using var factory = _factory.WithWebHostBuilder(builder =>    {        builder.ConfigureTestServices(services =>        {            services.RemoveAll<IPaymentGateway>();            services.AddSingleton<IPaymentGateway>(                new FakePaymentGateway { IsApproved = false });        });    });    using var client = factory.CreateClient();    using var response = await client.PostAsJsonAsync(        "/api/orders", new        {            customerId = "customer-001",            items = new[]            {                new { productId = "product-001", quantity = 1 }            }        });    response.StatusCode.Should().Be(HttpStatusCode.PaymentRequired); }

This pattern leaves the default factory unchanged for other tests. It is particularly useful when tests run in parallel and shared mutable state could cause interference.

Managing test configuration safely

Do not place real secrets or production connection strings in test code. Use fake URLs, temporary connection strings, and non-sensitive values. An appsettings.Testing.json file can usually be committed to source control, but it must not contain real passwords, tokens, personal data, or production endpoints.

Options validation helps ensure that test configuration is complete and valid:

public sealed class PaymentOptions {    public required string BaseUrl { get; init; } } builder.Services.AddOptions<PaymentOptions>()    .BindConfiguration("Payment")    .Validate(options => Uri.TryCreate(        options.BaseUrl,        UriKind.Absolute,        out _));

Configuration providers are evaluated according to their order. If the same key exists in multiple providers, the value from the higher-priority source wins. Therefore, after adding test values, verify that the application is not accidentally using a production value.

Common mistakes

  • Calling a real external service: The integration test becomes dependent on network availability, quotas, credentials, and third-party outages.
  • Adding a fake without removing the original: The application may resolve an unexpected implementation. Remove existing registrations when necessary.
  • Sharing mutable fake state: Parallel tests can race on fields such as CallCount or configurable results.
  • Loading a production connection string: Set the environment explicitly and validate critical configuration before tests start.
  • Ignoring disposal: Dispose WebApplicationFactory and clients appropriately, especially when creating per-test factories.
  • Replacing the wrong service: If application code depends directly on a concrete class, replacing an interface registration will not affect it. Depend on abstractions.

Short practice exercise

  1. Create an IClock interface and a production implementation in the API project.
  2. Register the production implementation so that it returns DateTimeOffset.UtcNow.
  3. Replace it in the custom factory with a FakeClock that returns a fixed date.
  4. Test that the order response contains the expected fixed createdAt value.
  5. Add a test that confirms the application runs in the Testing environment.

Conclusion

A custom WebApplicationFactory gives us controlled access to the ASP.NET Core application lifecycle during integration tests. With ConfigureWebHost, ConfigureAppConfiguration, ConfigureTestServices, and WithWebHostBuilder, we can add test-specific settings and replace production dependencies with fakes or mocks.

A well-designed test host keeps the real HTTP pipeline, isolates external systems, improves repeatability, and prevents accidental use of production configuration. In the next lesson, we will connect this infrastructure to database integration tests and test-data lifecycle management.

Sources