Covers WebApplicationFactory and TestServer: bootstrapping Program, ConfigureTestServices to swap dependencies, a test authentication handler for protected endpoints, per-test configuration, isolation and what in-memory tests do and do not prove.
WebApplicationFactory<Program> (package Microsoft.AspNetCore.Mvc.Testing) starts your real Program, with its middleware, routing, model binding, filters and DI, on an in-memory TestServer. CreateClient() returns an HttpClient that calls it without opening a socket.
ConfigureWebHost with builder.ConfigureTestServices(s => { s.RemoveAll<IPaymentGateway>(); s.AddSingleton<IPaymentGateway, FakeGateway>(); }). It runs after the app's own registrations, so the last one wins.AuthenticationHandler under a "Test" scheme that builds a ClaimsPrincipal from a header, so [Authorize] and policies run for real.IClassFixture), with unique or reset data per test.The trade-off: very high confidence in the HTTP contract for millisecond-level cost, but no real Kestrel, TLS or network.
"
WebApplicationFactory<TEntryPoint>boots the application exactly the way production does: it runsProgram, builds the host and swaps Kestrel forTestServer, an in-memory server that turns anHttpRequestMessagestraight into anHttpContext. So when I callclient.PostAsJsonAsync("/orders", dto)I'm exercising routing, model binding, validation, filters, authorisation, my handler, serialisation and ProblemDetails, all in a few milliseconds, with no port and no network.To control dependencies I subclass the factory and override
ConfigureWebHost.ConfigureTestServicesruns after the app's ownConfigureServices, so IRemoveAll<IPaymentGateway>()and add a fake, and I point theDbContextat a Testcontainers SQL Server rather than swapping it for the in-memory provider. For authentication I don't turn it off; I register a smallAuthenticationHandlerunder a "Test" scheme that reads a header likeX-Test-Userand builds claims. That way[Authorize(Policy = \"CanRefund\")]still runs, and I can write a test proving that a user without the claim gets a 403. For example, at [company] we [had an endpoint whose policy was accidentally removed in a refactor]; a test exactly like that caught it [in the PR].For isolation I share one factory per test class with
IClassFixture, because building the host costs a few hundred milliseconds, and isolate data instead: each test creates its own customer with a unique id, or I reset with Respawn. The mistake I see is replacing so much that the test only proves the fakes work, or usingAllowAnonymouseverywhere so security is never tested. Fake the edges you don't own, keep everything else real."
| Piece | What it does |
|---|---|
WebApplicationFactory<Program> |
Finds the entry point, builds the host, swaps in TestServer |
ConfigureWebHost(IWebHostBuilder) |
Your hook: environment, settings, test services |
ConfigureTestServices |
Runs after app registrations, so replacements win |
UseSetting(key, value) |
Overrides configuration (connection strings, feature flags) |
CreateClient(options) |
HttpClient wired to TestServer; set AllowAutoRedirect, BaseAddress |
WithWebHostBuilder(...) |
Derived factory for one test's special setup |
Services |
Root provider; create a scope to seed or inspect data |
| Keep real | Fake or replace |
|---|---|
| Middleware, routing, model binding, validation | Third-party HTTP APIs (WireMock.Net) |
| Authorisation policies | Authentication handler (test scheme) |
| EF Core and SQL (Testcontainers) | TimeProvider (FakeTimeProvider) |
| Serialisation and ProblemDetails | Email, SMS, payment gateways |
An orders API had 1,100 unit tests but kept breaking its contract: a renamed property, a missing [FromBody], a 500 instead of a 400 for bad input. Adding 85 WebApplicationFactory tests against a Testcontainers SQL Server added 40 seconds to CI and caught 9 contract regressions in the next quarter before they reached the mobile team.
Checks whether the candidate can write realistic in-memory API tests and knows how DI overrides, authentication and isolation work under the hood.
Green flags
Red flags
WebApplicationFactory<Program>
|
|-- finds Program's assembly, sets content root
|-- HostFactoryResolver intercepts WebApplication.CreateBuilder(args)
| (your Program runs until app.Run())
|-- applies ConfigureWebHost overrides
|-- replaces IServer (Kestrel) with TestServer
v
HttpClient --> TestServer handler --> HttpContext --> your middleware pipeline
The factory uses a diagnostic listener to catch the host when Build() is called, applies your overrides, then stops Program before Run() blocks. That's why Program must be reachable: with top-level statements older versions needed public partial class Program { }. The .NET 10 web SDK generates that declaration for you.
DI registrations are a list; resolving a single service returns the last registration. ConfigureTestServices callbacks run after the application's builder.Services calls, so anything you add there is last. RemoveAll<T>() is still worth calling, because IEnumerable<T> resolution would otherwise return both.
TestServer creates an in-memory HttpMessageHandler. Requests never hit a socket, so there's no TLS, HTTP/2 negotiation, connection limits, ForwardedHeaders from a real proxy or request size limits enforced by Kestrel. .NET 10 adds UseKestrel() on the factory to start a real Kestrel server for tests that need a real port, such as Playwright browser tests.
Authentication is pluggable: AddAuthentication("Test").AddScheme<AuthenticationSchemeOptions, TestAuthHandler>("Test", _ => { }). The handler's HandleAuthenticateAsync returns AuthenticateResult.Success(ticket) with the claims you want, or NoResult() to simulate an anonymous caller. Policies, roles and resource-based handlers then run for real. Setting it as the default scheme in ConfigureTestServices means [Authorize] uses it without changing production code.
Building the host takes roughly 200 to 800 ms depending on the app. Sharing a factory across a class (or a collection) amortises that. Each CreateClient() is cheap. Because the root IServiceProvider is shared, singletons (caches, in-memory stores) leak between tests in the same factory: reset them or create a derived factory with WithWebHostBuilder.
errors dictionary.TimeProvider with FakeTimeProvider and test an endpoint whose output depends on the date.IClassFixture across 50 tests.An orders endpoint with a policy, and xUnit v3 tests using a custom factory with a fake gateway and a test authentication scheme:
// Program.cs (code under test, abbreviated)
using Microsoft.AspNetCore.Authorization;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication().AddJwtBearer();
builder.Services.AddAuthorizationBuilder()
.AddPolicy("CanRefund", p => p.RequireClaim("permission", "orders.refund"));
builder.Services.AddSingleton<IPaymentGateway, StripeGateway>();
builder.Services.AddProblemDetails();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapPost("/orders/{id:int}/refund", async (int id, IPaymentGateway gateway, CancellationToken ct) =>
await gateway.RefundAsync(id, ct) ? Results.NoContent() : Results.Problem(statusCode: 409))
.RequireAuthorization("CanRefund");
app.Run();
public interface IPaymentGateway { Task<bool> RefundAsync(int orderId, CancellationToken ct); }
public sealed class StripeGateway : IPaymentGateway
{
public Task<bool> RefundAsync(int orderId, CancellationToken ct) => throw new NotSupportedException("Real call");
}
// ApiFactory.cs + RefundTests.cs (xunit.v3, Microsoft.AspNetCore.Mvc.Testing)
using System.Net;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Xunit;
namespace Orders.Api.Tests;
public sealed class FakeGateway : IPaymentGateway
{
public List<int> Refunded { get; } = [];
public Task<bool> RefundAsync(int orderId, CancellationToken ct) { Refunded.Add(orderId); return Task.FromResult(true); }
}
// Builds a principal from the X-Test-Permissions header; no header = anonymous.
public sealed class TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string Scheme = "Test";
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.TryGetValue("X-Test-Permissions", out var perms)) return Task.FromResult(AuthenticateResult.NoResult());
var claims = perms.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)
.Select(p => new Claim("permission", p))
.Append(new Claim(ClaimTypes.NameIdentifier, "test-user"));
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme));
return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme)));
}
}
public sealed class ApiFactory : WebApplicationFactory<Program>
{
public FakeGateway Gateway { get; } = new();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Testing");
builder.ConfigureTestServices(services =>
{
// Runs after Program's registrations, so these replace the real ones.
services.RemoveAll<IPaymentGateway>();
services.AddSingleton<IPaymentGateway>(Gateway);
services.AddAuthentication(TestAuthHandler.Scheme)
.AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.Scheme, _ => { });
});
}
}
public sealed class RefundTests(ApiFactory factory) : IClassFixture<ApiFactory>
{
private HttpClient ClientWith(string? permissions)
{
var client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false });
if (permissions is not null) client.DefaultRequestHeaders.Add("X-Test-Permissions", permissions);
return client;
}
[Fact]
public async Task Anonymous_caller_gets_401() =>
Assert.Equal(HttpStatusCode.Unauthorized,
(await ClientWith(null).PostAsync("/orders/7/refund", null, TestContext.Current.CancellationToken)).StatusCode);
[Fact]
public async Task Caller_without_permission_gets_403() =>
Assert.Equal(HttpStatusCode.Forbidden,
(await ClientWith("orders.read").PostAsync("/orders/7/refund", null, TestContext.Current.CancellationToken)).StatusCode);
[Fact]
public async Task Caller_with_permission_refunds_through_gateway()
{
var response = await ClientWith("orders.refund").PostAsync("/orders/8/refund", null, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Contains(8, factory.Gateway.Refunded);
}
}
AllowAnonymous, a policy that always succeeds). Why it is wrong: Security rules are never tested and a removed policy goes unnoticed. Instead: Use a test authentication scheme and assert 401, 403 and 200 cases.DbContext for the EF Core in-memory provider. Why it is wrong: No SQL translation, constraints, transactions or concurrency, so tests pass on queries that fail in SQL Server. Instead: Use Testcontainers SQL Server or at least SQLite, and reset data with Respawn.IClassFixture or a collection fixture and isolate data.IEnumerable<T> get both, and decorators may wrap the wrong one. Instead: RemoveAll<T>() before adding the replacement.WithWebHostBuilder for a fresh host.WebApplicationFactory tests are usually the best value tests in an API: they cover the HTTP contract, DI wiring, validation and security with almost no flakiness. I aim for every endpoint to have at least a happy path, a validation failure and an authorisation failure at this level, and keep unit tests for complex domain logic only.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| WebApplicationFactory + TestServer | Contract, wiring, security of an API | Host start per factory, in-memory only | Testing TLS, proxies, HTTP/2 specifics |
| WebApplicationFactory + UseKestrel (.NET 10) | Browser tests with Playwright | Real port, slower | Plain API contract tests |
| Deployed smoke tests | Proving the release works | Environment needed | Broad behaviour coverage |
| Unit tests of handlers | Complex rules with many cases | Miss pipeline and binding | Simple CRUD endpoints |
Measure suite time per test and failure causes: if most failures come from fakes being wrong, you are faking too much.
Use WebApplicationFactory<Program> to start the real app in memory and send real HTTP requests through the whole pipeline: middleware, routing, model binding, validation, DI, authorisation and JSON. Run the things you own for real, including EF Core against a real SQL Server in Testcontainers, because that is where mapping, translation and migration bugs live. Fake the things you don't own: third-party HTTP APIs (WireMock.Net), email and SMS, the clock (FakeTimeProvider), and usually the identity provider via a test authentication handler. Keep tests isolated by resetting data between tests with Respawn and sharing one container per test collection. The trade-off is a few seconds of start-up for far more confidence than mocks give.
Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.
Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.
Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.
How to tell it (STAR)
**S:** At [company] we moved our orders API from controllers to Minimal APIs, and a security review later found the refund endpoint had lost its policy. **T:** I owned fixing it and making sure it couldn't happen again. **A:** I restored the policy the same day, then found the root cause in our tests: they turned authentication off. I wrote a test authentication handler driven by a header, added 401/403/200 tests for every protected endpoint, and a test that fails if any endpoint has no authorisation metadata. **R:** We covered [42] endpoints in two days, the suite caught [2] more policy mistakes in the following quarter, and refunds by unauthorised users dropped to zero.
Last updated 23 Nov 2026.