Unit tests are not enough. Integration tests verify your app works end-to-end, including middleware, dependency injection, and database logic. `WebApplicationFactory` spins up an in-memory test host.
Setup
public class IntegrationTest : IClassFixture<WebApplicationFactory<Program>>
{
private readonly HttpClient _client;
public IntegrationTest(WebApplicationFactory<Program> factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task Get_ReturnsSuccess()
{
var response = await _client.GetAsync("/api/todos");
response.EnsureSuccessStatusCode();
}
}
Customizing Services
Replace the real database with an in-memory one.
factory.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.RemoveAll<DbContextOptions<MyDbContext>>();
services.AddDbContext<MyDbContext>(opt => opt.UseInMemoryDatabase("Test"));
});
});
Key Takeaways
- Use **Testcontainers** (covered earlier) for real SQL testing.
- Check HTTP status codes, response bodies, and headers.
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.