WebApplicationFactory bootstraps an in-memory version of a real ASP.NET Core application for integration tests. It uses the application's configuration, dependency-injection services, and middleware pipeline, letting tests send HTTP requests and verify responses. section 36.3 section 36.3.2
A basic integration test follows these steps:
- Add the Microsoft.AspNetCore.Mvc.Testing package. section 36.3.2
- Implement IClassFixture<WebApplicationFactory<Program>> on the test class and inject the factory. section 36.3.2
- Expose a public Program class when top-level statements make the generated class internal. section 36.3.2
Replacing an external dependency
When an application calls a third-party exchange-rate API, define and use an ICurrencyConverter interface. A test can replace the real implementation with StubCurrencyConverter through WithWebHostBuilder() and ConfigureTestServices(), then assert that the endpoint returns the controlled value. Repeated replacements can move into a custom factory that overrides ConfigureWebHost. section 36.3.3 section 36.3.4
Listing 36.8 Creating an integration test with WebApplicationFactory
public class IntegrationTests: #1
IClassFixture<WebApplicationFactory<Program>> #1
{
private readonly WebApplicationFactory<Program> _fixture; #2
public IntegrationTests( #2
WebApplicationFactory<Startup> fixture) #2
{ #2
_fixture = fixture; #2
} #2
[Fact]
public async Task PingRequest_ReturnsPong()
{
HttpClient client = _fixture.CreateClient(); #3
var response = await client.GetAsync("/ping"); #4
response.EnsureSuccessStatusCode(); #4
var content = await response.Content.ReadAsStringAsync(); #4
Assert.Equal("pong", content); #4
}
}
Use the complete listing to see fixture registration, factory injection, client creation, an in-memory request, and response verification together. section 36.3.2

