Integration Tests: The Dress Rehearsal

Integration Tests: The Dress Rehearsal in C#: Every performer has rehearsed alone. The lead knows every line, the lighting operator knows every cue, the…

The Analogy: The Dress Rehearsal

Every performer has rehearsed alone. The lead knows every line, the lighting operator knows every cue, the stagehand can move the sofa in eight seconds flat. None of that tells you whether the show works, because the show is what happens when they all do it at once — and the dress rehearsal is the first time anyone finds out that the sofa blocks the door the lead needs to leave through.

Unit tests are the individual rehearsals. They are fast, precise, and they prove that each piece behaves as its author intended. Integration tests are the dress rehearsal: the real routing, the real model binding, the real serialiser, the real middleware pipeline, the real database, all running together, driven through the front door with an HTTP request.

The bugs found in a dress rehearsal are almost never bugs of logic. They are bugs of fit: the property name the serialiser emits is not the one the client reads, the route constraint rejects an id the client sends, the transaction is never committed, the authorisation policy nobody wired up denies everything, the connection string points at a database that exists only on one laptop. Each component was correct. The seam was not.

What makes a dress rehearsal viable is that it is still a rehearsal. No audience, no real money, no real email leaving the building. ASP.NET Core gives you exactly that with WebApplicationFactory: your actual application, started in-process, with no socket ever opened and with any dependency you choose swapped for a safe one.


Syntax or Core Structure

The test project references the web project and the MVC testing package:

dotnet new xunit -o Shop.Api.Tests
cd Shop.Api.Tests
dotnet add reference ../Shop.Api/Shop.Api.csproj
dotnet add package Microsoft.AspNetCore.Mvc.Testing

Top-level statements compile to an internal Program class, so a test in another assembly cannot name it. One line at the bottom of Program.cs fixes that — and it is the first thing everybody gets stuck on:

// Program.cs, after all the top-level statements
public partial class Program
{
}

Now the factory boots the whole application and hands you a client wired straight into it:

using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

// IClassFixture means the host is booted once for the whole class, not per test.
public sealed class CatalogueApiTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public CatalogueApiTests(WebApplicationFactory<Program> factory)
    {
        // No port, no socket. The client talks to an in-memory transport.
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task The_health_endpoint_answers_ok()
    {
        HttpResponseMessage response = await _client.GetAsync("/health");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal("healthy", await response.Content.ReadAsStringAsync());
    }

    [Theory]
    [InlineData("/api/products")]
    [InlineData("/api/products/1")]
    public async Task Catalogue_endpoints_answer_with_json(string path)
    {
        HttpResponseMessage response = await _client.GetAsync(path);

        response.EnsureSuccessStatusCode();
        Assert.Equal("application/json", response.Content.Headers.ContentType?.MediaType);
    }
}

Output: (dotnet test, abridged — the build banner, assembly path and durations removed)

Passed!  - Failed:     0, Passed:     3, Skipped:     0, Total:     3

Three tests, and every layer of the application ran in each of them: UseRouting, the endpoint's model binding, the JSON serialiser with the application's real options, whatever exception handler is registered, and the real dependency graph from Program.cs. What did not run is the network — CreateClient returns an HttpClient whose handler hands the request directly to the pipeline, so there is no port to conflict with and no firewall prompt in CI.

Two details in that snippet decide how fast the suite is. IClassFixture<WebApplicationFactory<Program>> boots the host once per class rather than once per test, which matters because building a host is the expensive part. And the client is created in the constructor, so each test gets a fresh HttpClient over a shared host — cheap, and it avoids cookies or default headers leaking between tests.


Technical Depth: The Machinery Behind The Curtain

What WebApplicationFactory does for you

MemberPurpose
CreateClient()An HttpClient over the in-memory transport, BaseAddress http://localhost
CreateClient(options)Control AllowAutoRedirect, HandleCookies, BaseAddress
ConfigureWebHost (override)Change the host for every client this factory makes
WithWebHostBuilder(...)A new factory with extra configuration, for one awkward test
ServicesThe application's root provider — resolve a DbContext to seed or assert
ServerThe underlying TestServer, for CreateHandler or AllowSynchronousIO
ClientOptionsDefaults for every client the factory creates

It replaces Kestrel with TestServer, so requests never touch a socket: no ports, no TLS, no localhost firewall dialog in CI, and a request that would take 3 ms over a loopback takes microseconds. It also sets the content root to the web project's directory using an assembly attribute the SDK generates, which is why static files and appsettings.json resolve correctly.

The hook you want for swapping dependencies is ConfigureTestServices, because it runs after everything Program.cs registered:

using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection.Extensions;

HttpClient client = factory
    .WithWebHostBuilder(builder =>
    {
        builder.UseSetting("Features:NewPricing", "true");

        builder.ConfigureTestServices(services =>
        {
            services.RemoveAll<IPaymentGateway>();
            services.AddSingleton<IPaymentGateway, AlwaysApprovesGateway>();
        });
    })
    .CreateClient();

Registering a second IPaymentGateway without removing the first leaves both in the container: a constructor asking for IPaymentGateway gets the last registration, but one asking for IEnumerable<IPaymentGateway> gets the real one too. RemoveAll first, every time.

Choosing what the database is

StrategyIsolationFidelityNotes
Real engine in Docker (Testcontainers)Per run or per classHighestReal SQL, real constraints; slowest to start
Real engine, wiped between tests (Respawn)Per testHighestFast after the first boot; needs care with identity seeds
Transaction rolled back per testPer testHighBreaks if the code under test commits or uses its own connection
SQLite in-memoryPer connectionMediumFast and dependency-free; different SQL dialect and no schema parity
EF Core InMemory providerPer nameLowNo foreign keys, no transactions, no SQL — it will pass tests that production fails
Shared development databaseNoneHighTwo developers, one row, intermittent failures

The InMemory provider deserves its warning. It is a dictionary pretending to be a database: it accepts a duplicate primary key pattern the real engine rejects, ignores [Required] at the storage level and cannot execute raw SQL. Tests that pass against it prove that your LINQ compiles.

SQLite in-memory is the pragmatic middle. One rule governs it: the database exists only while its connection is open, so hold the SqliteConnection in a field for the fixture's lifetime rather than letting EF Core open and close one per operation.

Configuration, environment and secrets

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    builder.UseEnvironment("Testing");                        // picks up appsettings.Testing.json
    builder.UseSetting("ConnectionStrings:Shop", "DataSource=:memory:");

    builder.ConfigureAppConfiguration(config =>
    {
        config.AddInMemoryCollection(new Dictionary<string, string?>
        {
            ["Email:Enabled"] = "false",
            ["Payments:Endpoint"] = "http://localhost/not-used"
        });
    });
}

An integration test must never reach a real payment provider, a real mail server or a production connection string, and the reliable way to guarantee that is to make the test environment's configuration point at nothing usable. If a test fails with a connection error to a real host, that is a bug in the test setup, not a flake.

Authentication without a login

Two approaches, and both are legitimate:

// 1. A test scheme that always succeeds, for testing everything except auth.
public sealed class TestAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
    public TestAuthHandler(
        IOptionsMonitor<AuthenticationSchemeOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder)
        : base(options, logger, encoder)
    {
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        Claim[] claims =
        {
            new Claim(ClaimTypes.NameIdentifier, "test-user"),
            new Claim(ClaimTypes.Role, "buyer")
        };

        ClaimsPrincipal principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Test"));
        return Task.FromResult(AuthenticateResult.Success(
            new AuthenticationTicket(principal, "Test")));
    }
}

The second approach is to issue a real token signed with a test key and leave the real JWT middleware in place. It is slower to set up and it is the only way to prove that your audience, issuer and expiry validation are configured correctly — so most suites use the test handler for feature tests and keep a handful of real-token tests for the auth configuration itself. Whichever you choose, keep at least one test asserting that an anonymous request is rejected; a factory that always authenticates can hide a missing RequireAuthorization.

Parallelism, and the resource everybody shares

xUnit runs test classes in parallel, and two classes each booting a factory means two hosts pointed at whatever the connection string says. If that is one shared database, the suites interleave and fail on each other's rows.

  • Give each class its own database — a fresh SQLite connection per factory does this automatically.
  • Or put the classes that share a database in one [Collection] so they queue.
  • Or wipe and re-seed in IAsyncLifetime.InitializeAsync, which runs before every test in the class.

How much to test here

Integration tests are for the seams, not for every branch. Cover the round trip that proves persistence really happens, the serialised shape a client depends on, the status codes for the obvious failures, the authorisation boundary, and any endpoint whose bugs would be expensive. Push the combinatorics — every validation rule, every rounding case — down into unit tests where they cost a millisecond each.

dotnet test --filter "Category!=Integration"     # the fast loop while you work
dotnet test                                      # everything, in CI

Real World Example: The Bug Every Unit Test Missed

The two endpoints below passed their unit tests. The repository was faked, the fake stored what it was given, and the assertions were green. Read them and see whether you can spot what a dress rehearsal will find:

// Shop.Api/Program.cs, the interesting half
app.MapPost("/api/orders", async (CreateOrder request, ShopContext db) =>
{
    Product? product = await db.Products.SingleOrDefaultAsync(p => p.Sku == request.Sku);

    if (product is null)
    {
        return Results.NotFound();
    }

    if (request.Quantity < 1)
    {
        return Results.ValidationProblem(new Dictionary<string, string[]>
        {
            ["quantity"] = new[] { "quantity must be 1 or more" }
        });
    }

    Order order = new Order
    {
        Sku = request.Sku,
        Quantity = request.Quantity,
        TotalMinorUnits = product.PriceMinorUnits * request.Quantity
    };

    db.Orders.Add(order);

    return Results.Created(
        "/api/orders/" + order.Id,
        new OrderResponse(order.Id, order.Sku, order.Quantity, order.TotalMinorUnits));
});

app.MapGet("/api/orders/{id:int}", async (int id, ShopContext db) =>
{
    Order? order = await db.Orders.FindAsync(id);

    return order is null
        ? Results.NotFound()
        : Results.Ok(new OrderResponse(
            order.Id, order.Sku, order.Quantity, order.TotalMinorUnits));
});

The factory keeps one SQLite connection open for its whole life, and re-seeds on demand:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

public sealed class ShopApiFactory : WebApplicationFactory<Program>
{
    private readonly SqliteConnection _connection;

    public ShopApiFactory()
    {
        // Opened here and never closed: an in-memory database dies with its connection.
        _connection = new SqliteConnection("DataSource=:memory:");
        _connection.Open();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");

        // ConfigureTestServices runs after everything Program.cs registered.
        builder.ConfigureTestServices(services =>
        {
            services.RemoveAll<DbContextOptions<ShopContext>>();
            services.RemoveAll<ShopContext>();

            services.AddDbContext<ShopContext>(options => options.UseSqlite(_connection));
        });
    }

    // Called before every test: same schema, same seed, no leftovers.
    public async Task ResetAsync()
    {
        using IServiceScope scope = Services.CreateScope();
        ShopContext db = scope.ServiceProvider.GetRequiredService<ShopContext>();

        await db.Database.EnsureCreatedAsync();      // a no-op after the first test

        await db.Orders.ExecuteDeleteAsync();        // EF Core 7 and later
        await db.Products.ExecuteDeleteAsync();

        db.Products.AddRange(
            new Product { Sku = "bolt", PriceMinorUnits = 250 },
            new Product { Sku = "nut", PriceMinorUnits = 100 });

        await db.SaveChangesAsync();
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
        _connection.Dispose();
    }
}
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Http;
using Xunit;

public sealed class OrdersApiTests : IClassFixture<ShopApiFactory>, IAsyncLifetime
{
    private readonly ShopApiFactory _factory;
    private readonly HttpClient _client;

    public OrdersApiTests(ShopApiFactory factory)
    {
        _factory = factory;
        _client = factory.CreateClient();
    }

    // The host is shared across the class; the data is not.
    public Task InitializeAsync() => _factory.ResetAsync();

    public Task DisposeAsync() => Task.CompletedTask;

    [Fact]
    [Trait("Category", "Integration")]
    public async Task An_order_can_be_created_and_read_back()
    {
        HttpResponseMessage created = await _client.PostAsJsonAsync(
            "/api/orders", new { sku = "bolt", quantity = 3 });

        Assert.Equal(HttpStatusCode.Created, created.StatusCode);

        string? location = created.Headers.Location?.ToString();
        Assert.NotNull(location);

        HttpResponseMessage fetched = await _client.GetAsync(location);

        Assert.Equal(HttpStatusCode.OK, fetched.StatusCode);

        OrderResponse? order = await fetched.Content.ReadFromJsonAsync<OrderResponse>();

        Assert.NotNull(order);
        Assert.Equal(750, order!.TotalMinorUnits);
    }

    [Fact]
    [Trait("Category", "Integration")]
    public async Task An_unknown_order_is_not_found()
    {
        HttpResponseMessage response = await _client.GetAsync("/api/orders/9999");

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

    [Fact]
    [Trait("Category", "Integration")]
    public async Task A_zero_quantity_comes_back_as_a_field_error()
    {
        HttpResponseMessage response = await _client.PostAsJsonAsync(
            "/api/orders", new { sku = "bolt", quantity = 0 });

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);

        HttpValidationProblemDetails? problem =
            await response.Content.ReadFromJsonAsync<HttpValidationProblemDetails>();

        Assert.NotNull(problem);
        Assert.Contains("quantity", problem!.Errors.Keys);
    }

    [Fact]
    [Trait("Category", "Integration")]
    public async Task An_unknown_sku_is_not_found_rather_than_a_server_error()
    {
        HttpResponseMessage response = await _client.PostAsJsonAsync(
            "/api/orders", new { sku = "flange", quantity = 1 });

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

    [Fact]
    [Trait("Category", "Integration")]
    public async Task The_seeded_catalogue_is_visible()
    {
        ProductResponse[]? products =
            await _client.GetFromJsonAsync<ProductResponse[]>("/api/products");

        Assert.NotNull(products);
        Assert.Equal(2, products!.Length);
        Assert.Contains(products, p => p.Sku == "bolt" && p.PriceMinorUnits == 250);
    }
}

Output: (dotnet test, abridged — durations, stack traces, paths and the build banner removed)

  Failed An_order_can_be_created_and_read_back
  Error Message:
   Assert.Equal() Failure: Values differ
   Expected: OK
   Actual:   NotFound

Failed!  - Failed:     1, Passed:     4, Skipped:     0, Total:     5

The missing line is await db.SaveChangesAsync(); after db.Orders.Add(order). With it in place:

Passed!  - Failed:     0, Passed:     5, Skipped:     0, Total:     5

This is the canonical dress-rehearsal bug. The unit test that covered this endpoint used a fake repository whose AddAsync stored the order immediately, so "add then read" worked. EF Core's change tracker does not store anything until SaveChangesAsync, and nothing in the endpoint's own code is wrong in isolation — the seam between "the object is tracked" and "the row exists" is where it fails, and only a test that actually crosses that seam can see it.

The response even looked correct: 201 Created, with a Location header. Look closely at what that header contained, though — /api/orders/0, because a database-generated key is 0 until the insert happens. Reading order.Id before the commit is the same bug wearing a second disguise, and it is a strong argument for asserting on the round trip rather than on the creation response alone. A test that stopped at Assert.Equal(HttpStatusCode.Created, ...) would still be green today.

The other four tests are cheap and each guards a seam rather than a rule. An_unknown_sku_is_not_found_rather_than_a_server_error exists because a missing null check here is a 500 in production and a page of stack trace in the logs; A_zero_quantity_comes_back_as_a_field_error pins the errors dictionary a client's form binding reads, which no unit test of the validator can see; and The_seeded_catalogue_is_visible proves the real serialiser emits the property names the deserialiser on the other side expects. Notice that none of them re-tests the pricing arithmetic — that belongs in a unit test, where all twelve cases cost a millisecond.

IAsyncLifetime.InitializeAsync calling ResetAsync is what keeps them independent. The host is expensive and shared through IClassFixture; the data is cheap and rebuilt per test, which means these five tests can be reordered, run individually, or have a sixth inserted between them without anything changing. That is the property to protect, and the few milliseconds a re-seed costs is the cheapest insurance in the suite.


Common Mistakes

  1. Forgetting public partial class Program { }. Top-level statements make Program internal, so WebApplicationFactory<Program> will not compile from the test assembly until you declare it public or add [assembly: InternalsVisibleTo].
  2. Registering a replacement without removing the original. AddSingleton<IPaymentGateway, Fake> on top of the real registration leaves both; anything resolving IEnumerable<IPaymentGateway> still gets the real one.
  3. Letting the SQLite connection close. An in-memory database exists only while its connection is open, so a fixture that opens one per operation gets an empty schema on the second query.
  4. Using the EF Core InMemory provider and calling it an integration test. It has no foreign keys, no transactions and no SQL; it will pass tests that the real engine fails.
  5. Sharing one database across parallel test classes. Two factories, one connection string, interleaved rows, and failures that only appear on the CI machine's core count.
  6. Booting the host per test. IClassFixture exists for this. Per-test hosts turn a two-second suite into a two-minute one.
  7. Testing every business rule through HTTP. Ten rounding cases as integration tests cost a thousand times what they cost as unit tests and tell you nothing extra.
  8. A factory that authenticates everything. Convenient, and it hides a missing RequireAuthorization. Keep at least one test proving an anonymous request is rejected.

Best Practices

  • Drive tests through the front door. A real HttpClient request exercises routing, binding, filters, serialisation and the pipeline; calling the handler method directly skips all five.
  • Share the host, rebuild the data. IClassFixture for the factory, IAsyncLifetime for the seed, and every test stays independent without paying to boot a host.
  • Assert the round trip, not just the write. A 201 with a Location header proves nothing until a follow-up GET returns the resource.
  • Point the test environment at nothing real. No production connection string, no live payment endpoint, no mail server. A test that can reach production is a matter of time.
  • Prefer a real engine when fidelity matters. Testcontainers or a wiped local instance for anything involving SQL, constraints or migrations; SQLite in-memory when speed matters more than dialect.
  • Cover seams, not branches. Serialised shape, status codes, persistence, authorisation boundaries and the endpoints whose failure is expensive — and push combinatorics to unit tests.
  • Tag them and keep the fast loop fast. [Trait("Category", "Integration")] plus dotnet test --filter "Category!=Integration" while you work, everything in CI.
  • Test the migration path, not just the schema. Database.MigrateAsync() in the fixture proves the migrations apply cleanly; EnsureCreated silently skips them.

Practice Exercises

  1. The round trip that catches a missing commit. Build a two-endpoint API over EF Core with SaveChangesAsync deliberately omitted, then write the POST-then-GET integration test that fails. Fix it, and add a second assertion on the Location header proving the id is not zero.
  2. Swap a dependency at the seam. Give your API an outbound IPaymentGateway and use WithWebHostBuilder plus ConfigureTestServices to replace it — once with a stub that approves, once with one that throws. Assert 201 in the first case and your chosen failure status in the second, and confirm no real HTTP call leaves the process.
  3. Authorisation, both ways. Add a test authentication handler with a buyer role, then write three tests: an authenticated buyer succeeds, an authenticated user without the role gets 403, and an anonymous request gets 401. Then remove RequireAuthorization from the endpoint and check which tests go red.
  4. Two providers, one suite. Run the same test class against SQLite in-memory and against a real engine (Docker or a local instance), driven by a fixture parameter. Note any test that passes on one and fails on the other, and write down what that difference tells you about the value of each strategy.