ASP.NET Core › Health Checks
How would you write an integration test verifying that your health check endpoint correctly reports Unhealthy when a dependency is down?
IntermediateAnswer
Using WebApplicationFactory, override the DI registration for the dependency being tested (replacing a real database connection with a fake that simulates a failure) via ConfigureTestServices, then issue a request to /health via the test client and assert both the HTTP status code (503 for Unhealthy by default) and, if using a custom JSON response writer, the specific failing check's name in the response body.
public class HealthCheckTests : IClassFixture<WebApplicationFactory<Program>> {
[Fact]
public async Task Health_ReturnsUnhealthy_WhenDatabaseDown() {
var factory = _factory.WithWebHostBuilder(builder => {
builder.ConfigureTestServices(services => {
services.AddHealthChecks().AddCheck("database", () => HealthCheckResult.Unhealthy());
});
});
var client = factory.CreateClient();
var response = await client.GetAsync("/health");
Assert.Equal(HttpStatusCode.ServiceUnavailable, response.StatusCode);
}
}Real-world example A test suite verifies the /health endpoint correctly returns a 503 status when a simulated database check fails, giving confidence the health check wiring itself is correct before relying on it in a production Kubernetes deployment.