How do you write integration tests that work consistently for both controller-based and minimal API endpoints using WebApplicationFactory?
Short answer
WebApplicationFactory spins up an in-memory test server hosting the full application (regardless of whether its endpoints are controllers or minimal APIs, since both ultimately register into the same endpoint routing system) and issues real HTTP requests via an HttpClient --…
Advertisement
AModel answer
WebApplicationFactory<T> spins up an in-memory test server hosting the full application (regardless of whether its endpoints are controllers or minimal APIs, since both ultimately register into the same endpoint routing system) and issues real HTTP requests via an HttpClient -- from the test's perspective, there's no difference in how you write tests against either style, since you're testing observable HTTP behavior (status codes, response bodies) rather than the internal implementation mechanism.
public class ProductApiTests : IClassFixture<WebApplicationFactory<Program>> {
private readonly HttpClient _client;
public ProductApiTests(WebApplicationFactory<Program> factory) => _client = factory.CreateClient();
[Fact]
public async Task GetProduct_ReturnsOk() {
var response = await _client.GetAsync("/api/products/1"); // works identically whether this is a controller action or minimal API endpoint
response.EnsureSuccessStatusCode();
}
}Real-world example
A test suite covering both legacy controller-based endpoints and newly-migrated minimal API endpoints uses the exact same WebApplicationFactory-based testing pattern for both, requiring zero test code changes as endpoints are incrementally migrated from one style to the other.
Likely follow-ups
- Does this testing approach reveal any behavioral differences between the two styles at all?
- How would you unit test (not integration test) a minimal API handler function in isolation?
Related topics