Skip to content
Tutorials Center
My learning

Topics

Lesson 160 of 182 ยท Testing and Quality

Integration Testing ASP.NET Core

Test ASP.NET Core apps end to end with WebApplicationFactory - real routing, middleware and DI, replacing services and configuration, databases, authentication, and runnable examples.

A unit test proves that one class does its job. It cannot prove that the application as a whole answers POST /orders with the right status code, that your route template matches, that a middleware does not swallow the request, or that the JSON the client sends really binds to your model. Those failures live in the wiring: routing, model binding, filters, dependency injection, serialization. Integration tests exercise that wiring by sending real HTTP requests to your real application, running in the same process as the test.

ASP.NET Core was designed to make this cheap. You can start the whole app with its real Program.cs inside a test, swap out only the pieces that touch the outside world (a clock, an email service, a database), and send requests with an HttpClient. In this lesson you will learn the standard tool for this, WebApplicationFactory, and then build the same pattern yourself in runnable code, so you understand every moving part. If you are new to testing, read Testing Fundamentals and Mocks, Stubs and Fakes first; the app being tested here is a minimal API.

Unit, integration and end-to-end

flowchart LR
    U["Unit tests<br/>one class, no I/O"] --> I["Integration tests<br/>whole app in-process,<br/>external systems replaced"] --> E["End-to-end tests<br/>deployed system,<br/>real browser or client"]

Moving right, tests cover more of the real system, but they become slower, more fragile and harder to diagnose.

Integration tests sit in the middle: they run in milliseconds to a few seconds, need no deployment, and still catch the bugs that unit tests cannot. A healthy suite has many unit tests, a moderate number of integration tests for the important request paths, and very few end-to-end tests.

WebApplicationFactory: the standard tool

The package Microsoft.AspNetCore.Mvc.Testing provides WebApplicationFactory<TEntryPoint>. It builds your application using your real startup code, hosts it on an in-memory test server (no network port is opened) and hands you an HttpClient that talks to it directly. Here is the whole setup in a test project. It is read-only here because the package is not part of the shared framework in our runner:

C#
// Read-only: needs the Microsoft.AspNetCore.Mvc.Testing and xunit NuGet packages.
// In the web project, make the generated Program class visible to tests:
public partial class Program { }      // or add <InternalsVisibleTo> in the csproj

// In the test project:
public class OrdersApiTests(WebApplicationFactory<Program> factory)
    : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client = factory.CreateClient();

    [Fact]
    public async Task Post_creates_an_order_and_returns_201()
    {
        var response = await _client.PostAsJsonAsync("/orders", new { item = "Tea", quantity = 2 });

        Assert.Equal(HttpStatusCode.Created, response.StatusCode);
        Assert.NotNull(response.Headers.Location);
    }

    [Fact]
    public async Task Unknown_order_returns_404()
    {
        var response = await _client.GetAsync("/orders/9999");

        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
    }
}

The test never calls a controller method directly. The request goes through the full pipeline (see Middleware): routing, authentication, model binding, validation, your handler, serialization. A typo in a route attribute or a missing AddScoped registration now fails a test.

IClassFixture<WebApplicationFactory<Program>> makes xUnit create the factory once per test class and share it, because starting an app is the expensive part. The shared app means shared state, so tests must not depend on each other (more on that below).

Replacing services and configuration

Tests must not send real email or charge real cards. WithWebHostBuilder lets you change the app's configuration just for a test; ConfigureTestServices runs after the app's own registrations, so your replacement wins:

C#
// Read-only: needs Microsoft.AspNetCore.Mvc.Testing
var client = factory.WithWebHostBuilder(builder =>
{
    builder.UseSetting("Payments:Mode", "Sandbox");          // configuration override

    builder.ConfigureTestServices(services =>
    {
        services.RemoveAll<IEmailSender>();                    // drop the real one
        services.AddSingleton<IEmailSender, RecordingEmailSender>();
        services.AddSingleton<TimeProvider>(new FixedTimeProvider(
            new DateTimeOffset(2030, 1, 1, 0, 0, 0, TimeSpan.Zero)));
    });
}).CreateClient();

This is the same seam idea as in the mocking lesson, applied to a whole application: dependency injection is what makes the swap possible, and registering time as TimeProvider makes dates testable.

The pattern in runnable code

We can show the mechanism without the package. Our runner's own technique, used throughout the ASP.NET lessons, is to start a real Kestrel server on a loopback port and call it with HttpClient. A tiny helper that builds the app, applies optional service overrides, starts it, gives the test a client and stops it afterwards is exactly what a factory does. The app below is the code under test: an orders API with a repository and a clock.

C# A test factory for an orders API

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Study how the helper maps to WebApplicationFactory: OrdersApp.Create is "run the real Program", the overrides callback is ConfigureTestServices, UseUrls plus new HttpClient stands in for CreateClient(), and the try/finally guarantees the app is stopped even when an assertion fails. The two bottom tests do not mock any method calls: they swap in a fixed clock and a broken repository, then assert on what the HTTP client sees. That is the strength of this style. The error test checks the whole behavior, including the exception handler middleware, which a unit test of the endpoint lambda would never touch.

Overriding configuration and testing middleware

Configuration is the other thing tests often change: feature flags, API keys, connection strings. Add an in-memory source in the test, and the app reads it through the normal configuration system, as covered in Configuration and Options. The next example tests a cross-cutting concern, an API key check implemented as middleware, and varies the key per test:

C# Testing middleware with configuration overrides

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The last test is a nice example of something only integration tests reveal: order matters. Because the header middleware is registered before the key check, even a rejected request carries the header. Move the registration and the test fails, which is the point.

Databases in integration tests

Most real apps have a database, and the key question is what to use in tests. The options, from fastest to most realistic:

Option Speed Realism Caveat
EF Core UseInMemoryDatabase Very fast Low It is not a relational database: no constraints, no transactions, no SQL translation. Many bugs pass.
SQLite in memory Fast Medium A real relational engine, but SQL dialect and types differ from SQL Server or PostgreSQL.
The real engine in a container (for example Testcontainers) Slower High Needs Docker on the machine and in CI, but tests what you will run.

Whatever you choose, each test needs a known starting state. Typical strategies are a fresh database per test class, a transaction rolled back after each test, or a cleanup tool that resets tables between tests. The factory shape for swapping the database looks like this:

C#
// Read-only: needs EF Core and Microsoft.AspNetCore.Mvc.Testing
builder.ConfigureTestServices(services =>
{
    services.RemoveAll<DbContextOptions<ShopContext>>();          // remove the production registration
    services.AddDbContext<ShopContext>(o => o.UseSqlite(_connection));
});

Keep a single open SqliteConnection for the factory's lifetime, because an in-memory SQLite database vanishes when its connection closes. The data-layer side of this is in Entity Framework Core.

Authentication in tests

You usually do not want a test to sign in through a real identity provider. Two common approaches:

  1. A test authentication scheme. Register a handler that always authenticates a fixed user (with the roles and claims the test needs) and make it the default scheme in ConfigureTestServices. The rest of the pipeline ([Authorize], policies) runs for real.
  2. Real tokens signed with a test key. The app is configured with the test key and the test creates a JWT. This also exercises token validation.

Test both the happy path (a user with the right role gets 200) and the forbidden ones (anonymous gets 401, wrong role gets 403). Authorization rules are security-critical, so they deserve explicit tests. The concepts are in Authentication and Authorization.

What to assert, and what not to

  • Status code and headers first. 201 with a Location, 400 with a problem-details body (Validation and Problem Details), 404, 401/403.
  • Body contracts. Deserialize into a DTO and compare the fields that matter. Avoid asserting an entire JSON string character by character; field order and whitespace are not behavior.
  • Side effects. Check what the fake email sender or the repository received.
  • Not internals. Do not assert on private methods or the number of calls to a service; assert on what a client could observe.

Keep the suite fast and reliable: share the factory per class, never share mutable state between tests, avoid Thread.Sleep (wait for conditions instead), run tests in CI on every change, and give failing tests clear names that say which request and which expectation failed.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What kind of bug can an integration test catch that a unit test of the endpoint's handler method usually cannot?

    Routing, model binding, filters and DI registration are part of the pipeline, not of the handler method. Only a request sent through the real application exercises them.
  2. 2. In WebApplicationFactory tests, why is ConfigureTestServices the right place to replace a service?

    The test registrations are applied after the application's services, which is why a replacement registered there takes effect.
  3. 3. Why do integration tests need a known starting state?

    If one test leaves data behind that another relies on, results change with execution order. Fresh state per test (or cleanup between tests) keeps them independent.
  4. 4. What is the main weakness of EF Core's in-memory provider for integration tests?

    The in-memory provider just stores objects, so unique indexes, foreign keys, transactions and SQL translation problems all go unnoticed.
  5. 5. A test asserts that the X-Content-Type-Options header is present on a 401 response. What does that verify?

    Because the header middleware runs earlier in the pipeline than the key check that short-circuits, the header is set before the 401 is produced. Order is behavior.

Summary

  • Integration tests send real requests through the real pipeline, so they catch wiring bugs (routing, binding, DI, middleware order) that unit tests miss.
  • WebApplicationFactory<Program> hosts your app in memory and gives you an HttpClient; expose Program with public partial class Program { }.
  • Replace external dependencies with ConfigureTestServices and override settings with UseSetting or an in-memory configuration source.
  • Prefer fakes (fixed clock, recording email sender, in-memory or real test database) and assert on what a client can observe.
  • Give every test a known starting state; share the expensive factory per class but never share mutable data between tests.
  • Replace authentication with a test scheme or test-signed tokens, and test both allowed and forbidden requests.

Next: Source Generators and Roslyn