All 15 Global Exception Handling & Middleware questions
More in Global Exception Handling & Middleware
Advertisement
Back to results for “Global Exception Handling & Middleware”
.NET › Global Exception Handling & Middleware

How do you write an integration test verifying that your global exception handler produces the correct error response shape?

Intermediate

Answer

Using WebApplicationFactory<T> to spin up an in-memory test server, you can create a test-only endpoint or use an existing one that deliberately throws a known exception, then assert on the actual HTTP response's status code and JSON body shape returned by the real exception handling middleware -- verifying the full pipeline behavior rather than just unit testing the handler class in isolation.
public class ExceptionHandlingTests : IClassFixture<WebApplicationFactory<Program>> {
    [Fact]
    public async Task NotFoundException_Returns404WithProblemDetails() {
        var client = _factory.CreateClient();
        var response = await client.GetAsync("/api/products/99999");
        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        var problem = await response.Content.ReadFromJsonAsync<ProblemDetails>();
        Assert.Equal("Resource not found", problem.Title);
    }
}
Real-world example A team adds an integration test suite specifically verifying error response shapes for each custom exception type, catching a regression where a refactor accidentally changed the JSON field name from 'title' to 'Title', breaking client-side error parsing.

Common follow-ups: How does WebApplicationFactory differ from a full end-to-end test against a real deployed instance?;What's the value of testing the actual pipeline versus just unit testing the handler class directly?