Microsoft.AspNetCore.Mvc.Testing provides infrastructure for testing a real ASP.NET Core application in memory. WebApplicationFactory runs the application with its configuration, dependency-injection services, and complete middleware pipeline, while using TestServer behind the scenes. This gives integration tests a closer view of production behavior than isolated component tests. section 36.3.2 section 36.5
A basic integration test follows this pattern:
- Add the Microsoft.AspNetCore.Mvc.Testing NuGet package to the test project. section 36.3.2
- Implement IClassFixture<WebApplicationFactory<Program>> on the test class and inject the factory. section 36.5
- Call CreateClient(), send HTTP requests, and assert the responses. section 36.3.2
- Expose a public Program or Startup class when the generic factory cannot reference the app entry point. section 36.3.2
Testing a ping endpoint
An integration test creates a client from WebApplicationFactory<Program>, sends GET /ping, calls EnsureSuccessStatusCode(), and can then verify that the response contains "pong". section 36.3.2
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
}
}
Open the annotated listing for the complete fixture-based C# test structure. section 36.3.2
Customize a factory with WithWebHostBuilder and ConfigureTestServices to replace application services, such as a third-party API client stub. For repeated customization, derive a custom WebApplicationFactory and override ConfigureWebHost. section 36.5
