Advertisement
Advanced ASP.NET Core, Error Handling

How would you write an integration test verifying that your global exception handler produces the correct error response shape for a specific exception type?

Short answer

Using WebApplicationFactory to spin up an in-memory test server, 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…

Save ASP.NET Core mock interview
Advertisement
AModel answer
Using WebApplicationFactory<T> to spin up an in-memory test server, 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.
[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.
Likely 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?
Related topics