Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 8 · Lesson 73 · 7 min read

ASP.NET Core Integration Testing with Testcontainers

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: The Factory, the Test Scheme, Respawn and a Stubbed Provider
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Build a reusable integration test harness with a custom WebApplicationFactory, a real SQL Server container, a test authentication scheme and database resets between tests, fake external HTTP dependencies, and keep the suite fast, isolated and safe from leaking into production code.

Concept Explanation

On Days 20 and 40 you wrote your first integration tests. Now they need to scale to hundreds of tests without becoming slow or interdependent. The harness has five responsibilities. It starts the real application in memory, using WebApplicationFactory. It provides a real database, started once and shared by all tests, using a container. It authenticates test requests as specific users without going through an identity provider. It resets data between tests so they cannot influence each other. And it replaces outbound dependencies, such as payment and email services, with controlled fakes. Getting this harness right once means every later test is a few readable lines.

Starting a database container takes seconds, so it must be shared. An xUnit collection or class fixture starts the container once per test run, and the application factory reuses it. Isolation between tests then comes from resetting data instead of recreating the database. The Respawn library, by Jimmy Bogard, inspects the schema and generates efficient DELETE statements in dependency order, resetting the tables in a few milliseconds, which is far faster than dropping and migrating. Tell it which tables to keep, such as the migrations history and reference data. Running tests within a collection sequentially keeps the shared database safe, and you scale across collections or by giving each parallel worker its own database.

Authentication in tests should not depend on a real identity provider. Register a test authentication scheme that builds a principal from headers, so a test says which user and roles it acts as with one line. This handler must never exist in production: put it in the test project only, register it through ConfigureTestServices so it replaces the real scheme just for tests, and consider a startup check that fails if the test scheme is present in a non-test environment. Fake external services at the HTTP boundary with a tool like WireMock.Net, an implementation of the WireMock stub server that originated in Java, which lets you script responses, delays, and failures, so you can test the resilience behavior from Day 69 as well as the happy path.

Speed and reliability come from discipline. Seed only what each test needs, using the builders from Day 72, and create data through the same code paths the application uses, or directly through the DbContext, not through shared script files that nobody understands. Avoid sleeping: wait for conditions, such as an outbox message being published, using polling with a timeout. Capture application logs in the test output so a failure shows what the server did. Keep environment differences honest: use the same SQL Server image as production and run the same migrations. Finally, never let tests touch real secrets or real cloud resources; the container and the fakes are the whole world of the test.

ConcernTechniqueNote
Real app in memoryWebApplicationFactory of ProgramReal pipeline, routing, binding, filters
Real database, sharedTestcontainers fixture per runStart once, reuse for all tests
Isolation between testsRespawn resets data in millisecondsFaster than recreating the schema
AuthenticationTest scheme reading headersTest project only, never in production
External servicesWireMock.Net stubs at the HTTP boundaryScript failures and delays too
Async behaviorPoll for a condition with a timeoutNever fixed sleeps

Worked Example: The Factory, the Test Scheme, Respawn and a Stubbed Provider

The listings show the reusable harness, then a test that uses it, including a stubbed failing payment provider.

C#
public sealed class ApiFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly MsSqlContainer _sql = new MsSqlBuilder("mcr.microsoft.com/mssql/server:2022-latest").Build();
    public WireMockServer Payments { get; } = WireMockServer.Start();
    private Respawner _respawner = null!;

    public async Task InitializeAsync()
    {
        await _sql.StartAsync();
        Environment.SetEnvironmentVariable("ConnectionStrings__Default", _sql.GetConnectionString());
        Environment.SetEnvironmentVariable("Payments__BaseUrl", Payments.Url);

        using var scope = Services.CreateScope();                     // builds the host, applies migrations
        await scope.ServiceProvider.GetRequiredService<AppDb>().Database.MigrateAsync();

        await using var conn = new SqlConnection(_sql.GetConnectionString());
        await conn.OpenAsync();
        _respawner = await Respawner.CreateAsync(conn, new RespawnerOptions
        {
            TablesToIgnore = [new("__EFMigrationsHistory"), new("Roles")],
            WithReseed = true,
        });
    }

    public async Task ResetAsync()
    {
        await using var conn = new SqlConnection(_sql.GetConnectionString());
        await conn.OpenAsync();
        await _respawner.ResetAsync(conn);
        Payments.Reset();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder) =>
        builder.ConfigureTestServices(services =>
        {
            services.AddAuthentication(TestAuthHandler.Scheme)
                    .AddScheme<AuthenticationSchemeOptions, TestAuthHandler>(TestAuthHandler.Scheme, _ => { });
            services.AddSingleton<TimeProvider>(new FakeTimeProvider(new DateTimeOffset(2026, 9, 1, 9, 0, 0, TimeSpan.Zero)));
            services.RemoveAll<IEmailSender>();
            services.AddSingleton<IEmailSender, CapturingEmailSender>();   // assert on sent mail without an SMTP server
        });

    public new async Task DisposeAsync() { Payments.Stop(); await _sql.DisposeAsync(); await base.DisposeAsync(); }
}

// Lives ONLY in the test project. Reads the acting user from headers.
public sealed class TestAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> o, ILoggerFactory l, UrlEncoder e)
    : AuthenticationHandler<AuthenticationSchemeOptions>(o, l, e)
{
    public const string Scheme = "Test";
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        if (!Request.Headers.TryGetValue("X-Test-User", out var user)) return Task.FromResult(AuthenticateResult.NoResult());
        var claims = new List<Claim> { new("sub", user!), new("tid", Request.Headers["X-Test-Tenant"].FirstOrDefault() ?? TestData.DefaultTenant.ToString()) };
        foreach (var role in Request.Headers["X-Test-Roles"].ToString().Split(',', StringSplitOptions.RemoveEmptyEntries)) claims.Add(new("role", role));
        var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme)), Scheme);
        return Task.FromResult(AuthenticateResult.Success(ticket));
    }
}

[CollectionDefinition("api")] public class ApiCollection : ICollectionFixture<ApiFactory>;
C#
[Collection("api")]
public class CheckoutTests : IAsyncLifetime
{
    private readonly ApiFactory _f;
    public CheckoutTests(ApiFactory f) => _f = f;
    public Task InitializeAsync() => _f.ResetAsync();                 // clean data before every test
    public Task DisposeAsync() => Task.CompletedTask;

    [Fact]
    public async Task A_payment_provider_outage_returns_503_with_retry_after_and_creates_no_order()
    {
        _f.Payments.Given(Request.Create().WithPath("/charges").UsingPost())
                   .RespondWith(Response.Create().WithStatusCode(500));   // the stubbed dependency fails

        var client = _f.CreateClient().AsUser("alice");
        var res = await client.PostAsJsonAsync("/api/orders", new { productId = TestData.ProductId, quantity = 1 });

        Assert.Equal(HttpStatusCode.ServiceUnavailable, res.StatusCode);
        Assert.NotNull(res.Headers.RetryAfter);
        await using var db = _f.NewDbContext();
        Assert.Empty(await db.Orders.ToListAsync());                   // no half-created state was left behind
    }

    [Fact]
    public async Task The_receipt_email_is_sent_after_the_outbox_is_published()
    {
        var client = _f.CreateClient().AsUser("alice");
        await client.PostAsJsonAsync("/api/orders", new { productId = TestData.ProductId, quantity = 1 });

        var sent = await Eventually.ForAsync(() => _f.Emails.Sent, s => s.Count == 1, timeout: TimeSpan.FromSeconds(5));   // poll, never sleep
        Assert.Equal("alice@example.test", sent.Single().To);
    }
}

public static class ClientExtensions
{
    public static HttpClient AsUser(this HttpClient c, string user, string roles = "", Guid? tenant = null)
    {
        c.DefaultRequestHeaders.Add("X-Test-User", user);
        if (roles != "") c.DefaultRequestHeaders.Add("X-Test-Roles", roles);
        if (tenant is { } t) c.DefaultRequestHeaders.Add("X-Test-Tenant", t.ToString());
        return c;
    }
}
TypeScript
// Guard rail: the test scheme must never be present outside tests. Put this in the real Program.cs startup.
var schemes = await app.Services.GetRequiredService<IAuthenticationSchemeProvider>().GetAllSchemesAsync();
if (!app.Environment.IsEnvironment("Testing") && schemes.Any(s => s.Name == "Test"))
    throw new InvalidOperationException("The test authentication scheme is registered outside a test environment.");

The outage test is the kind that only a real pipeline and real database can give you: it proves that the resilience configuration, exception mapping, and transaction handling work together, including that no partial order remains after the failure.

An ApiFactory runs the real app with a test-only authentication scheme and fake clock. A shared SQL Server container is reset between tests by Respawn, and outbound payment calls hit a WireMock stub.
An ApiFactory runs the real app with a test-only authentication scheme and fake clock. A shared SQL Server container is reset between tests by Respawn, and outbound payment calls hit a WireMock stub.

Real-World Examples

  • The Respawn library, created by Jimmy Bogard, was designed to solve the cost of resetting databases between integration tests by computing the delete order from foreign key relationships, and is used widely in .NET projects following his integration-testing-first approach to vertical slice architecture. Resetting data in milliseconds is what makes hundreds of database-backed tests practical.
  • WireMock began as a Java library by Tom Akehurst for stubbing HTTP APIs in tests, and its model of request matching and scripted responses was ported to other platforms including WireMock.Net. Stubbing at the HTTP boundary, instead of mocking client classes, means your tests exercise the real HttpClient configuration, including timeouts, retries, and serialization.
Key TakeawaysBuild the integration test harness once and reuse it everywhere: a factory that runs the real ASP.NET Core app against real dependencies. Add a shared Testcontainers database reset with Respawn, a test-only authentication scheme, and stubbed HTTP dependencies. Poll for asynchronous outcomes instead of sleeping, capture logs, use the production database engine, and add guard rails so test-only components can never be active in a real environment.

Review Questions & Answers

Creating a database and applying migrations takes seconds per test, which makes a large suite unbearably slow. Respawn deletes rows from every table in the correct dependency order in a few milliseconds, giving each test a clean state while reusing the same schema and container.

If it were ever active in a real environment, anyone could authenticate as any user by sending a header. Containing it means defining it only in the test project, registering it through ConfigureTestServices, and adding a startup guard that throws if the test scheme exists outside a test environment.

Stubbing at the HTTP boundary exercises the real HttpClient pipeline, including the resilience handler, timeouts, serialization, and error mapping, so the test proves those pieces work together. Mocking the client class skips all of that and only proves the caller handles the mock's behavior.

A fixed sleep is either too short, causing flaky failures on a slow machine, or too long, wasting time in every run. Polling with a timeout continues as soon as the condition is met and only fails if it truly never happens, making tests both faster and more reliable.