Lesson 7 of 9 · 28m
Testing .NET Services with WebApplicationFactory and Real Boundaries
Build a test pyramid that catches behavior regressions with fast unit tests, API-level integration tests, and controlled external dependencies.
The most dangerous test suite is not the one with no tests; it is the one with hundreds of green tests that never touch a real boundary. I've watched teams mock the database, mock the HTTP client, mock the clock, and then discover in production that the real migration never ran. Tests should buy confidence at the cheapest honest layer. Everything else is ceremony.
Test behavior at the appropriate seam
Pure domain logic belongs in fast unit tests:
[Fact]
public void Rejecting_paid_order_is_invalid()
{
var order = Order.Paid(customerId: Guid.NewGuid(), total: 42m);
var result = order.Cancel();
Assert.False(result.Success);
}HTTP behavior, model binding, authorization, serialization, and database interaction belong in integration tests. Do not contort a unit test to prove framework behavior.
WebApplicationFactory tests the host you actually run
WebApplicationFactory<TEntryPoint> boots the application in memory and lets you replace selected dependencies:
public sealed class ApiFixture : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services.RemoveAll<IEmailSender>();
services.AddSingleton<IEmailSender, FakeEmailSender>();
});
}
}A test then exercises the real routing and serialization pipeline:
var response = await client.PostAsJsonAsync("/orders", new
{
lines = new[] { new { sku = "SKU-100", quantity = 2 } }
});
Assert.Equal(HttpStatusCode.Created, response.StatusCode);Use it to verify behavior, not to re-test ASP.NET itself. Replace only dependencies that are genuinely external; replacing the database with a dictionary can make the test fast and useless at the same time.
Integration tests need controlled infrastructure
For relational behavior, use the real database engine when possible. Testcontainers can start PostgreSQL for the fixture lifetime:
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
.Image("postgres:16-alpine")
.WithDatabase("orders_test")
.WithUsername("postgres")
.WithPassword("postgres")
.Build();Run migrations before tests, isolate each test class or collection, and reset state deliberately. In-memory providers are convenient for simple behavior, but they do not validate SQL translation, constraints, transactions, concurrency tokens, or provider-specific behavior.
Deterministic time and identity beat test flakiness
Inject TimeProvider or a clock abstraction where time affects behavior. Freeze it in tests:
var clock = new FakeTimeProvider(DateTimeOffset.Parse("2026-01-15T12:00:00Z"));
var service = new ReservationService(clock, repository);The same principle applies to GUID generation and randomness. A test that depends on wall-clock precision or random ordering will eventually fail at 2:13 in the morning and teach nobody anything.
Contract tests protect client trust
If an API is consumed by another team, test the contract shape, not merely status codes. Verify field names, nullability, enum representations, error shape, versioning behavior, and compatibility of additive changes. Snapshot tests can help, but reviewers must actually read the snapshots. A golden file nobody reviews is just automated complacency.
Field notes
- Parallel tests sharing one database create cross-test phantoms. Isolate schemas, databases, or fixture collections.
- Fake external clients should simulate timeouts and malformed responses, not only success paths.
- Do not assert implementation details such as 'method X was called' unless the interaction itself is the behavior.
- A slow integration suite is often a design signal: too much logic is trapped behind infrastructure boundaries.
Was this lesson helpful?