IClassFixture<TFixture> is an xUnit marker interface for sharing one fixture instance across every test in a class. xUnit creates the fixture before the test class and injects it into the constructor. section 36.3.2
Use WebApplicationFactory in an integration test
Declare IClassFixture<WebApplicationFactory<Program>>, accept WebApplicationFactory<Program> in the test constructor, and call CreateClient() to send in-memory requests through the real application configuration, services, and middleware pipeline. This lets a test request an endpoint such as /ping without starting Kestrel. section 36.3.2
Apply the fixture when:
- Tests need a shared application fixture rather than constructing one separately for each test. section 36.3.2
- Tests exercise several ASP.NET Core components together and need behavior close to production. section 36.5
- Tests must avoid real databases or third-party calls; customize WebApplicationFactory with ConfigureTestServices or a derived factory. section 36.3.2 section 36.5
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 annotated integration-test listing to see the fixture declaration, constructor injection, client creation, and request flow together. section 36.3.2
