Introduction
An API must handle invalid requests as carefully as it handles successful requests. A client needs to know whether a request was malformed, whether a business rule rejected it, whether a resource was not found, or whether the server experienced an unexpected failure. HTTP status codes and a consistent response body provide that contract.
In this lesson, we will extend the WebApplicationFactory-based integration test infrastructure from the previous lesson. The tests will travel through the real HTTP pipeline, including model binding, validation, controllers or endpoints, exception handling middleware, and ProblemDetails generation.
Assume that our sample application exposes POST /api/orders. A valid request creates an order. A missing customer identifier, a negative total, or an empty line collection should produce a validation response. Insufficient stock represents a domain failure, while an unexpected infrastructure failure should result in a safe generic server error.
The role of ProblemDetails and HTTP status codes
ProblemDetails provides a standardized, machine-readable structure for HTTP API errors. A response commonly contains fields such as type, title, status, detail, and a correlation or tracing identifier. Validation failures can additionally expose an errors dictionary containing messages grouped by field.
| Scenario | Expected status | Response type |
|---|---|---|
| Invalid JSON or missing required field | 400 Bad Request | ValidationProblemDetails |
| Business rule violation | 409 Conflict or, by application policy, 422 Unprocessable Entity | Customized ProblemDetails |
| Missing resource | 404 Not Found | ProblemDetails |
| Unexpected exception | 500 Internal Server Error | Generic ProblemDetails |
A useful test does more than assert the status code. It should also verify the content type, the required problem fields, the validation keys, and the absence of sensitive implementation details.
Configuring the application error pipeline
Tests are valuable only when the application has a deliberate and predictable error policy. With minimal hosting, a basic ASP.NET Core configuration can look like this:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers();builder.Services.AddProblemDetails();builder.Services.AddExceptionHandler<GlobalExceptionHandler>();var app = builder.Build();app.UseExceptionHandler();app.UseStatusCodePages();app.MapControllers();app.Run();public partial class Program { }
AddProblemDetails enables standard problem responses where appropriate. UseExceptionHandler prevents production clients from receiving stack traces and internal exception details. In integration tests, enabling a developer exception page without considering the test contract can produce HTML or detailed exception output instead of the JSON response the API is supposed to expose.
Mapping domain exceptions in one central handler is usually easier to maintain than repeating exception handling in every controller:
public sealed class GlobalExceptionHandler : IExceptionHandler{ private readonly IProblemDetailsService _problemDetails; public GlobalExceptionHandler(IProblemDetailsService problemDetails) { _problemDetails = problemDetails; } public async ValueTask<bool> TryHandleAsync( HttpContext httpContext, Exception exception, CancellationToken cancellationToken) { if (exception is InsufficientStockException stockException) { httpContext.Response.StatusCode = StatusCodes.Status409Conflict; return await _problemDetails.TryWriteAsync(new ProblemDetailsContext { HttpContext = httpContext, ProblemDetails = new ProblemDetails { Title = "Order cannot be created", Detail = stockException.Message, Status = StatusCodes.Status409Conflict, Type = "https://example.test/problems/insufficient-stock" } }); } httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError; return await _problemDetails.TryWriteAsync(new ProblemDetailsContext { HttpContext = httpContext, ProblemDetails = new ProblemDetails { Title = "An unexpected error occurred", Status = StatusCodes.Status500InternalServerError } }); }}
In a real application, problem type URIs, user-facing messages, logging, and correlation behavior should follow the project’s API contract. The integration tests protect that contract from accidental changes.
Shared integration-test helpers
We can reuse the CustomWebApplicationFactory<Program> and xUnit fixture introduced in the previous lesson. To keep the tests readable, add a small JSON helper or a base class:
public sealed record ProblemResponse( string? Type, string? Title, int? Status, string? Detail, string? TraceId, Dictionary<string, string[]>? Errors);public abstract class ApiTestBase{ protected readonly HttpClient Client; protected ApiTestBase(CustomWebApplicationFactory<Program> factory) { Client = factory.CreateClient(); } protected static StringContent Json(object value) => new(JsonSerializer.Serialize(value), Encoding.UTF8, "application/json");}
Representing the fields used by the test explicitly is safer than scattering anonymous JSON access throughout the test suite. However, the DTO must match the application’s actual JSON naming policy and customized ProblemDetails writer. Do not assume that every application serializes property names in exactly the same way.
Testing validation failures
Suppose the request model looks like this:
public sealed class CreateOrderRequest{ [Required] public Guid? CustomerId { get; init; } [Range(0.01, 100000)] public decimal Total { get; init; } [Required] public List<OrderLineRequest> Lines { get; init; } = [];}
When the controller uses [ApiController], invalid model state can automatically produce a response before the action executes. Verify that behavior through the HTTP client:
public sealed class OrderApiTests : IClassFixture<CustomWebApplicationFactory<Program>>{ private readonly HttpClient _client; public OrderApiTests(CustomWebApplicationFactory<Program> factory) { _client = factory.CreateClient(); } [Fact] public async Task Post_WithInvalidModel_ReturnsValidationProblemDetails() { var request = new { customerId = (Guid?)null, total = -10, lines = Array.Empty<object>() }; var response = await _client.PostAsync( "/api/orders", new StringContent( JsonSerializer.Serialize(request), Encoding.UTF8, "application/json")); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); response.Content.Headers.ContentType!.MediaType .Should().Be("application/problem+json"); var body = await response.Content .ReadFromJsonAsync<JsonElement>(); body.GetProperty("status").GetInt32() .Should().Be(400); body.GetProperty("errors").GetProperty("CustomerId") .GetArrayLength().Should().BeGreaterThan(0); body.GetProperty("errors").GetProperty("Total") .GetArrayLength().Should().BeGreaterThan(0); }}
This test verifies the combined behavior of the controller conventions, model binding, validation, and JSON serialization. The exact casing of validation keys depends on the JSON and MVC configuration. If the application uses camel case, assert against the actual contract rather than blindly assuming PascalCase.
Testing domain exceptions
Validation and domain exceptions are different concepts. Validation checks whether the request has the correct shape and values. A domain exception means that a structurally valid request violates a business rule. Insufficient stock is a typical example.
[Fact]public async Task Post_WhenStockIsInsufficient_ReturnsConflictProblemDetails(){ var request = new { customerId = Guid.NewGuid(), total = 125, lines = new[] { new { productId = Guid.NewGuid(), quantity = 100 } } }; var response = await _client.PostAsync( "/api/orders", new StringContent( JsonSerializer.Serialize(request), Encoding.UTF8, "application/json")); response.StatusCode.Should().Be(HttpStatusCode.Conflict); var body = await response.Content.ReadFromJsonAsync<JsonElement>(); body.GetProperty("title").GetString() .Should().Be("Order cannot be created"); body.GetProperty("status").GetInt32().Should().Be(409); body.GetProperty("type").GetString() .Should().Be("https://example.test/problems/insufficient-stock");}
The test data must reliably produce the domain exception. Seed a known product and stock quantity in the test database or reuse the deterministic seed mechanism created earlier. Sending a random product identifier can accidentally produce a 404, making the test unstable and misleading.
Testing unexpected failures
Unexpected exceptions must not expose stack traces, connection strings, SQL fragments, or internal exception messages to API clients. A controlled fake service can force the failure in an integration test:
public sealed class ThrowingOrderService : IOrderService{ public Task<OrderResult> CreateAsync( CreateOrderRequest request, CancellationToken cancellationToken) => throw new InvalidOperationException("Test failure");}[Fact]public async Task Post_WhenUnexpectedExceptionOccurs_ReturnsGenericServerProblem(){ using var factory = _factory.WithWebHostBuilder(builder => builder.ConfigureTestServices(services => { services.RemoveAll<IOrderService>(); services.AddScoped<IOrderService, ThrowingOrderService>(); })); using var client = factory.CreateClient(); var request = new { customerId = Guid.NewGuid(), total = 20, lines = new[] { new { productId = ExistingProductId, quantity = 1 } } }; var response = await client.PostAsync("/api/orders", Json(request)); response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); var text = await response.Content.ReadAsStringAsync(); text.Should().NotContain("Test failure"); text.Should().NotContain("System.InvalidOperationException");}
ConfigureTestServices lets this test replace a dependency without changing the normal application registration. Manage the factory and client lifetime carefully. The test is checking the public HTTP contract, not the internal implementation detail of how the exception handler logs or classifies the exception.
Content negotiation and the Accept header
The response content type can depend on the request’s Accept header and the registered ProblemDetails writer. If the API explicitly supports application/problem+json, make that expectation visible in the test:
_client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/problem+json"));
Do not assume that every configuration always returns exactly this media type. Some applications intentionally use application/json. The assertion should reflect the documented API contract, not a copied assumption from another project.
Common mistakes
- Checking only the status code: A 400 response is not enough. Verify that the body follows the expected problem format.
- Expecting production behavior in Development: The developer exception page may return HTML or detailed exception data.
- Confusing validation and domain failures: A missing field is normally 400, while a business conflict may be 409 or 422 according to application policy.
- Asserting sensitive details: Stack traces and internal exception messages are not stable API contract fields.
- Registering a test double incorrectly: If the original registration remains, the dependency injection container may resolve an unexpected implementation.
- Ignoring the request parsing stage: Malformed JSON can produce a different 400 response before normal model validation runs.
- Using one status code for every exception: The status code should help the client decide whether to fix the request, retry, or report a server failure.
Practice exercise
Task: Write three integration tests for POST /api/orders:
- Verify that a missing customerId returns 400 and includes the corresponding errors entry.
- Verify that insufficient stock returns 409, the expected problem type URI, and a user-appropriate title.
- Replace the order service with a throwing fake, then verify that the API returns 500 without exposing the exception message.
Keep each test focused on one observable behavior. Do not combine database seeding, authentication, validation, and exception handling into one oversized test unless that combination is the behavior you intentionally want to verify. Extract repeated setup into helper methods where appropriate.
Conclusion
In this lesson, we tested API failures through the real HTTP pipeline. We verified field-level ValidationProblemDetails for invalid requests, a meaningful conflict response for domain exceptions, and a safe generic 500 response for unexpected failures.
A strong integration test checks what an external client can observe rather than merely checking whether a method throws. Status code, media type, problem fields, validation keys, security boundaries, and error types should be considered together. With this approach, the API error contract becomes explicit, testable, and much less likely to regress as the application grows.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.problemdetailscontext?view=aspnetcore-10.0