What is WebApplicationFactory, and how do you write an integration test for a Web API?
Quick Answer
WebApplicationFactory<TEntryPoint> spins up your whole ASP.NET Core app in memory (real pipeline, real DI) and gives you an HttpClient to call it. You can override services (swap the real DB for an in-memory or containerised one, fake external clients) in ConfigureWebHost. Tests exercise routing, model binding, filters, auth and serialization for real.
WebApplicationFactory boots the entire app in memory — the real middleware pipeline, the real DI container — and hands me an HttpClient that calls it without a network. So I can send a real HTTP request and check the status code and body, and that exercises routing, model binding, filters and serialization end to end. In ConfigureWebHost I swap out the things I don't want real — I point the DbContext at a test database, ideally a SQL Server container via Testcontainers rather than the EF in-memory provider because that doesn't behave like real SQL, and I stub any outbound HTTP.
- Inherit
WebApplicationFactory<Program>and overrideConfigureWebHostto replace services — e.g. remove the realDbContextregistration and add one pointing at a test database. - Prefer a real database (SQLite file, or SQL Server via Testcontainers) over the EF in-memory provider — the in-memory provider doesn't enforce constraints or translate real SQL.
- Seed data per test, and reset between tests (respawn, transaction rollback, or a fresh container).
- Fake external HTTP dependencies with a stub
HttpMessageHandler.