Introduction
In the previous lesson, we tested controllers directly and verified whether their action methods produced the expected results. A controller test, however, does not fully represent an HTTP request traveling through the real application pipeline. To verify routing, model binding, JSON serialization, middleware, and HTTP response behavior together, we need to start the application in a test environment and send requests through a real HttpClient.
In this lesson, we will use ASP.NET Core's integration testing infrastructure and the WebApplicationFactory<TEntryPoint> class. The factory creates a test host from the application's entry point. We can then call CreateClient() to obtain an HTTP client connected to the in-memory test server. This allows us to perform end-to-end tests without opening a real network port.
Our examples will use the order API from the previous lessons. We will not replace the database or configure a custom authentication system yet. The goal is to build the first API integration tests in a simple and understandable way. Replacing external dependencies and configuring a test database will be covered in later lessons.
Integration testing approach: The test verifies routing, middleware, controller execution, serialization, and response generation as one application flow.
WebApplicationFactory and the test host
WebApplicationFactory<Program> is a factory that starts an ASP.NET Core application for testing. With the modern minimal hosting model, Program is the application's entry point. The factory runs the application on a TestServer and creates an HttpClient connected to that server.
These tests do not need a real browser or a real TCP port. Nevertheless, the request travels through the application's HTTP pipeline. As a result, we can test the following components together:
- Endpoint routing and route templates
- HTTP methods and status code behavior
- JSON request and response serialization
- Model binding and validation
- Exception handling and other middleware components
- Actual dependency injection resolution between controllers and application services
This scope is broader than a unit test. In return, integration tests can be slower and require more setup. We should therefore use unit tests and integration tests for different responsibilities rather than repeating every small business rule through HTTP.
Preparing the test project
The test project needs a project reference to the API project and the Microsoft.AspNetCore.Mvc.Testing package. For a test project targeting .NET 10, the package can be installed with:
dotnet add tests/OrderApi.Tests package Microsoft.AspNetCore.Mvc.Testing
The test project should already contain the xUnit and test SDK packages. Assume that the API project is named OrderApi and the test project is named OrderApi.Tests. Add the project reference with:
dotnet add tests/OrderApi.Tests reference src/OrderApi/OrderApi.csproj
For an application using minimal hosting, the following declaration at the end of the API project's Program.cs is a convenient way to expose the entry point to the test project:
public partial class Program { }
This enables the test project to use WebApplicationFactory<Program>. An assembly-level InternalsVisibleTo declaration is another option, but the public partial Program approach is more explicit for introductory integration tests.
Creating the first test class
Let's provide the factory to the test class as an xUnit fixture. When IClassFixture<T> is used, xUnit shares the fixture instance among the tests in that class.
using System.Net;using System.Net.Http.Json;using FluentAssertions;using Microsoft.AspNetCore.Mvc.Testing;namespace OrderApi.Tests;public sealed class OrdersApiTests : IClassFixture<WebApplicationFactory<Program>>{ private readonly HttpClient _client; public OrdersApiTests(WebApplicationFactory<Program> factory) { _client = factory.CreateClient(); }}
CreateClient() starts the application and returns a client connected to the test server. The default client can follow successful redirects. Redirects are not usually expected in API tests, so this behavior is not central here, but it is still important to understand that client options can be customized for a specific scenario.
Testing a GET endpoint
First, let's test an endpoint that returns a specific order. Assume that the API returns the following response for GET /api/orders/42:
{ "id": 42, "customerName": "Ada Lovelace", "status": "Pending"}
The test should verify the result at the HTTP level. Instead of checking only one value in the response body, it is more useful to inspect the status code, content type, and deserialized object together.
[Fact]public async Task Get_existing_order_returns_ok_and_json_body(){ // Arrange const int orderId = 42; // Act var response = await _client.GetAsync($"/api/orders/{orderId}"); // Assert response.StatusCode.Should().Be(HttpStatusCode.OK); response.Content.Headers.ContentType!.MediaType .Should().Be("application/json"); var order = await response.Content .ReadFromJsonAsync<OrderResponse>(); order.Should().NotBeNull(); order!.Id.Should().Be(orderId); order.CustomerName.Should().Be("Ada Lovelace"); order.Status.Should().Be("Pending");}public sealed record OrderResponse( int Id, string CustomerName, string Status);
Here, GetAsync behaves like a real HTTP client. We convert the JSON response to a DTO with ReadFromJsonAsync. This also brings serialization behavior into the test scope. If a response property is serialized with the wrong name or an expected field is missing, the test can expose the problem.
Testing routing and missing resources
One major advantage of integration tests is that they can detect errors in route definitions. The controller action may be correct while the route template is wrong. We should also verify that the API returns 404 NotFound for an order that does not exist.
[Fact]public async Task Get_unknown_order_returns_not_found(){ // Arrange const int unknownOrderId = 999999; // Act var response = await _client.GetAsync($"/api/orders/{unknownOrderId}"); // Assert response.StatusCode.Should().Be(HttpStatusCode.NotFound);}
For this test to remain reliable, we must know that order 999999 does not exist in the data source used by the test environment. This is acceptable when a fixed seed dataset is being used. In later lessons, we will discuss clearing and recreating test data before each test.
Testing a POST request and validation
Integration tests are not limited to GET endpoints. For POST endpoints with JSON request bodies, we can observe model binding and validation behavior as well. Assume the create request uses the following model:
public sealed record CreateOrderRequest( string CustomerName, decimal TotalAmount);
For a valid request:
[Fact]public async Task Post_valid_order_returns_created_response(){ // Arrange var request = new CreateOrderRequest( "Grace Hopper", 125.50m); // Act var response = await _client .PostAsJsonAsync("/api/orders", request); // Assert response.StatusCode.Should().Be(HttpStatusCode.Created); response.Headers.Location.Should().NotBeNull(); var createdOrder = await response.Content .ReadFromJsonAsync<OrderResponse>(); createdOrder.Should().NotBeNull(); createdOrder!.CustomerName.Should().Be("Grace Hopper");}
PostAsJsonAsync converts the request body to JSON and sends it with the appropriate content type. Returning Created together with a Location header is an important part of the REST API contract, so both should be checked.
We can also test the response for invalid data:
[Fact]public async Task Post_order_with_empty_customer_name_returns_bad_request(){ // Arrange var request = new CreateOrderRequest("", 125.50m); // Act var response = await _client .PostAsJsonAsync("/api/orders", request); // Assert response.StatusCode.Should().Be(HttpStatusCode.BadRequest);}
This test verifies not only that validation rules exist on the request model, but also that the rules are translated into the correct HTTP status code by the pipeline. If you use Problem Details, you can additionally verify the response content type and selected error fields. Avoid testing every implementation detail; focus on the API contract exposed to clients.
Separating the application environment
Tests should not connect to a production database or real external services. Because WebApplicationFactory starts the application during the test run, we can configure a separate environment. In this lesson we use the basic factory, but later we will change service registrations with ConfigureWebHost or WithWebHostBuilder.
For example, we can explicitly run the application in a test environment by creating a custom factory:
using Microsoft.AspNetCore.Hosting;using Microsoft.AspNetCore.Mvc.Testing;public sealed class TestWebApplicationFactory : WebApplicationFactory<Program>{ protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.UseEnvironment("Testing"); }}
The test class can then use IClassFixture<TestWebApplicationFactory>. The application may read test-specific settings from appsettings.Testing.json or other environment-specific configuration. However, changing only the environment name does not automatically isolate the database. If the application uses a real connection string, that registration must also be replaced.
Common mistakes
- Unable to access Program: An application using minimal hosting may require a public partial Program declaration so the test project can find the generic entry point.
- Using the wrong URL: If the controller route is api/orders, do not add or remove path segments in the test request.
- Checking only the status code: A response with status 200 can still contain an incorrect JSON body. Verify important response fields as well.
- Connecting tests to the production database: Integration tests can create, update, or delete data. Always isolate the test connection.
- Mixing unit and integration test responsibilities: Testing every business rule through HTTP makes the suite slower and harder to maintain.
- Sharing mutable state: Data created by one test should not silently change the starting conditions of another test.
Short practice exercise
Complete the following exercise:
- Create a test class that uses WebApplicationFactory<Program>.
- Verify that GET /api/orders returns 200 OK.
- Deserialize the response body into a list DTO and assert that the list is not empty.
- Inspect the result of GET /api/orders/not-a-number. Depending on your route constraint or model binding behavior, you may expect 400 or 404.
- Add a POST test and verify the status code, Location header, and JSON body of the created response.
The objective is not to write a large number of tests. It is to observe the complete chain from a request entering the test host to the response returned by the application.
Conclusion
In this lesson, we started an ASP.NET Core API in a test environment with WebApplicationFactory and wrote our first integration tests using a real HttpClient. We verified status codes, content types, JSON bodies, routing, and validation behavior for GET and POST requests.
Integration tests provide broader confidence than calling a controller directly because they use the application's actual dependency injection and middleware pipeline. At the same time, unit tests remain important for keeping the suite fast and focused. In the next stage, we will customize the factory, replace service dependencies, use a test database, and make API tests more isolated and predictable.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/testing/integration-testing
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.testing.webapplicationfactory-1?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.testing.webapplicationfactory-1.withwebhostbuilder?view=aspnetcore-10.0