Interview frequency: …
Short answer
It creates an in-memory test server (TestServer) that runs the real application pipeline and provides an HttpClient for sending requests and checking responses.
Explanation
Microsoft.AspNetCore.Mvc.Testing provides WebApplicationFactory, commonly used for Integration tests. It starts the actual Program.cs and runs all Middlewares, Routing, and authentication. With WithWebHostBuilder, you can replace specific services, such as replacing the database with Testcontainers or InMemory.
Code example
public class ApiTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>> {
private readonly HttpClient _client = factory.CreateClient();
[Fact]
public async Task Health_ReturnsOk() {
var res = await _client.GetAsync("/health");
Assert.Equal(HttpStatusCode.OK, res.StatusCode);
}
}Common mistakes
- Forgetting to make Program public with public partial class Program { } in Top-level statements projects, preventing the test project from accessing it.