skip to content

In an ASP.NET Core 10 WebApplicationFactory test, how do you replace the job-board API's registered e-mail sender with a fake for one test?

level: middleimportance: must knowfreq 66%

answer

  1. a derived factory per test
  2. WithWebHostBuilder returns a new factory
  3. ConfigureTestServices from Microsoft.AspNetCore.TestHost
  4. RemoveAll<T>() before adding the fake
  5. TryAdd* adds nothing if registered

basics

~10 s

Call factory.WithWebHostBuilder(b => b.ConfigureTestServices(s => { s.RemoveAll<IMailSender>(); s.AddSingleton<IMailSender>(fake); })). The callback runs after Program.cs's registrations, and the derived factory boots its own app, leaving the shared factory untouched.

solid answer

~40 s

`ConfigureTestServices` (an `IWebHostBuilder` extension in `Microsoft.AspNetCore.TestHost`) queues a service callback that runs after `Program.cs` has made its `builder.Services` calls and before the container is built. Inside it, remove the real registration with `RemoveAll<IMailSender>()` and add the fake, keeping a reference to the instance so the test can assert what was sent. To scope the swap to one test, call it inside `WithWebHostBuilder`: that returns a new `WebApplicationFactory<Program>` which runs the parent's configuration plus yours and boots a separate app with its own singletons; the parent tracks it in `Factories` and disposes it. For a swap every test needs, override `ConfigureWebHost` in a `WebApplicationFactory<Program>` subclass instead. `TryAddSingleton` does nothing once a registration exists, and a plain extra `AddSingleton` leaves the real sender in `IEnumerable<IMailSender>`.

code

csharp · 25 lines
csharp
using System.Net.Http.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

[Fact]
public async Task Applying_sends_one_confirmation_mail()
{
    var mailer = new RecordingMailSender();

    using var client = _factory
        .WithWebHostBuilder(builder => builder.ConfigureTestServices(services =>
        {
            services.RemoveAll<IMailSender>();
            services.AddSingleton<IMailSender>(mailer);
        }))
        .CreateClient();

    var response = await client.PostAsJsonAsync("/jobs/42/applications",
        new { CandidateEmail = "[email protected]" });

    response.EnsureSuccessStatusCode();
    Assert.Single(mailer.Sent);
}

go deeper

for a junior

Remember the two pieces: WithWebHostBuilder for a per-test factory and ConfigureTestServices to change registrations, with RemoveAll before adding the fake.

for a middle

Explain why the callback sees Program.cs registrations already in the collection, how RemoveAll, Replace, AddSingleton and TryAddSingleton differ, and why the fake instance is a singleton.

for a senior

Show the cost model: each derived factory boots a separate app, so group tests by override set, and remember hosted services and keyed registrations that a naive swap misses.

for a principal

Decide which collaborators a suite fakes at the factory level versus per test, and keep the test-only overrides small enough that the booted app still resembles production.

## The scenario The job-board API sends a confirmation mail when a candidate applies: `POST /jobs/{id}/applications` calls the app's own `IMailSender`, which `Program.cs` registers against an SMTP implementation. An integration test must not send real mail, and it wants to assert that exactly one confirmation went out. The answer has two parts: **where** the override goes and **how** it replaces the real registration. ## Where the override goes `WebApplicationFactory<Program>` offers two hooks, both receiving an `IWebHostBuilder`: | Hook | Scope | Typical use | |---|---|---| | override `ConfigureWebHost` in a subclass | every app the factory or its derived factories boot | test database, outbound fakes all tests share | | `WithWebHostBuilder(builder => ...)` | one new derived factory | a fake that only some tests need | `WithWebHostBuilder` does **not** change the running host. It returns a new factory that replays the parent's `ConfigureWebHost` and then your callback, and that factory boots **its own copy of the app** on first use, with its own singletons and its own run of `Program.cs`. The parent records it in the `Factories` list and disposes it with itself. The cost is a second startup, so tests that share the same overrides should share one derived factory. ## Why ConfigureTestServices and when it runs `ConfigureTestServices(Action<IServiceCollection>)` comes from `Microsoft.AspNetCore.TestHost`. With a `WebApplication` app the factory intercepts the host when `Program.cs` calls `builder.Build()`, and only then replays its own service callbacks, so they run: 1. after every `builder.Services.Add…` call in `Program.cs`; 2. before the `ServiceProvider` is built, so the container never sees the removed registration. On today's generic host, `ConfigureTestServices` simply forwards to `IWebHostBuilder.ConfigureServices`; the separate method exists because, with the old `WebHostBuilder` and a `Startup` class, `ConfigureServices` ran **before** `Startup.ConfigureServices` and would have been overwritten. Using `ConfigureTestServices` keeps the intent obvious and works for both shapes. ## How to replace the registration The service collection is a list of `ServiceDescriptor`s, and the choice of call matters: - **`RemoveAll<IMailSender>()` then `AddSingleton<IMailSender>(fake)`** is the robust pattern. Every unkeyed `IMailSender` descriptor disappears, so constructor injection, `GetRequiredService` and `IEnumerable<IMailSender>` all see only the fake. - **`Replace(ServiceDescriptor.Singleton<IMailSender>(fake))`** removes only the first matching descriptor, which is enough when the app registers one implementation. - **`AddSingleton` alone** adds a second descriptor. Single resolution returns the last one, so the obvious test passes, but anything that injects `IEnumerable<IMailSender>` still gets the SMTP sender. - **`TryAddSingleton`** adds nothing, because a registration for the type already exists; the real sender stays. - **Keyed services** need care: `RemoveAll<T>()` skips descriptors that carry a `ServiceKey`, so remove the keyed descriptor by hand and re-add it with `AddKeyedSingleton`. Registering the fake as a **singleton instance** you created in the test is what lets you assert on it afterwards: the app and the test hold the same object. If the real sender was scoped, a singleton fake is fine as long as it is thread-safe, because parallel requests share it. ## Things that stay real - Hosted services registered by the app still start with the host; if a `BackgroundService` sends mail on a timer, it needs the same treatment. - Options configured in `Program.cs` still bind from the app's configuration unless the test overrides them too. - The factory's environment is `Development`, so anything `Program.cs` registers only outside Development is absent in tests unless the environment is changed. ## Asserting through the app's own services Sometimes the evidence lives inside the app rather than in a fake: a row the endpoint wrote, a cache entry, a queued message. The factory exposes the booted app's root provider as `Services`, so a test can open a scope and resolve what it needs: - `using var scope = factory.Services.CreateScope();` then resolve the scoped service, such as the `DbContext`, from `scope.ServiceProvider`. - Use the `Services` of the **same** factory that served the request. A derived factory from `WithWebHostBuilder` is a separate app with separate singletons and, often, separate in-memory state. - Never resolve scoped services from the root provider directly; in Development the factory's scope validation throws. ## Mistakes worth naming in an interview - Calling `ConfigureTestServices` inside the shared fixture's factory for one test, which silently changes every other test using that factory. - Expecting `WithWebHostBuilder` to reconfigure a host that is already running. - Resolving the fake from `factory.Services` of the **parent** factory when the request went through the derived one; they are different apps.

  • Every test in the suite needs the fake mailer. Where should it go instead?
    Subclass `WebApplicationFactory<Program>` and override `ConfigureWebHost`, calling `builder.ConfigureTestServices(...)` there. One host is booted for all tests sharing that factory, while `WithWebHostBuilder` remains for the few tests that need an extra override on top.
  • The real sender is registered with AddKeyedScoped<IMailSender>("smtp", ...). Why does RemoveAll<IMailSender>() leave it in place?
    `RemoveAll` removes only descriptors whose `ServiceKey` is null, so keyed registrations survive. Remove the descriptor with that key from the collection yourself and register the fake with `AddKeyedSingleton<IMailSender>("smtp", fake)`.

  • ConfigureTestServices runs before Program.cs, so the app's registration wins.
  • TryAddSingleton in ConfigureTestServices overrides the app's real sender.
  • WithWebHostBuilder reconfigures the already running host in place.
  • A second AddSingleton removes the real sender from IEnumerable<IMailSender> too.
  • Changing the shared factory's services for one test affects no other test.