Wiring a Testcontainers SQL Server into WebApplicationFactory: container lifecycle with IAsyncLifetime, overriding the connection string, migrating once, resetting with Respawn, and sharing one container across classes with a database per class.
Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.
Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.
Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.
"
WebApplicationFactoryruns the real API in memory, with the full middleware pipeline, DI and routing, over aTestServer. Testcontainers gives me a real SQL Server in Docker. Together they test the API the way it runs in production, minus the network.The wiring is short. My
ApiFactoryderives fromWebApplicationFactory<Program>and implementsIAsyncLifetime.InitializeAsyncstarts anMsSqlContainer. Then I touchServicesto build the host, create a scope and callDatabase.MigrateAsync(), so the schema comes from my real migrations, notEnsureCreated. InConfigureWebHostI callUseSetting("ConnectionStrings:Orders", _container.GetConnectionString()), and the app's normalAddDbContextpicks it up.DisposeAsyncdisposes the container and then the base factory. Testcontainers also starts a small reaper container called Ryuk, which cleans up if the test process crashes.Between tests I reset with Respawn. It reads the foreign-key graph once and then runs ordered
DELETEs, typically 20 to 50 milliseconds, ignoring__EFMigrationsHistory. Used as anIClassFixture, every class gets its own container and database. When the suite grows I share one container and give each class its own database name, which saves 5 to 15 seconds of start-up per class. The mistake I see is using the EF Core in-memory provider instead. It doesn't enforce foreign keys or unique indexes, has no real transactions and doesn't translate LINQ to SQL, so the tests pass and production fails. Real SQL Server in a container is the only database test I trust."
| Piece | Role |
|---|---|
WebApplicationFactory<Program> |
Hosts the API in memory; CreateClient() returns an HttpClient wired to TestServer |
IAsyncLifetime |
Awaited start-up and cleanup of the container (ValueTask in xUnit v3) |
MsSqlContainer (Testcontainers.MsSql) |
Real SQL Server; GetConnectionString() includes the mapped random port |
UseSetting / ConfigureTestServices |
Point the app at the container, or swap services |
Database.MigrateAsync() |
Real schema, from the same migrations as production |
| Respawn | Fast data reset between tests |
| Option | Isolation | Start-up cost | Fits |
|---|---|---|---|
Container per class (IClassFixture<ApiFactory>) |
Strongest | 5-15 s Γ classes | Small suites |
| Shared container, database per class | Strong | One start-up + about 1-3 s migrate per class | Most suites |
| Shared container and database, collection + Respawn | Serial inside the collection | One start-up | Tests that need a known empty state |
In a typical orders API with around 200 endpoint tests across 25 classes, moving from a container per class to one shared container with a database per class cuts the integration stage from about 6 minutes to about 2. It also caught a missing unique index that the in-memory provider had happily ignored.
Checks whether the candidate can wire real infrastructure into in-memory API tests with the right lifecycle, schema and isolation choices.
Green flags
IAsyncLifetime to start and stop the container, and disposes in the right order.UseSetting or ConfigureTestServices and gets the connection string from the container.Red flags
WebApplicationFactory<TEntryPoint> finds your app's entry point (Program), runs its host-building code with a TestServer instead of Kestrel, and lets you hook in before the host is built.
Test ββHttpClientβββΆ TestServer (in memory, no sockets)
β
βΌ
your real pipeline: middleware β routing β endpoints β DI
β
βΌ
OrdersDbContext ββTCPβββΆ Docker: mcr.microsoft.com/mssql/server:2022
(random host port, started by Testcontainers)
The hooks run in this order: ConfigureWebHost (where UseSetting and ConfigureTestServices live), then your Program's registrations, then the ConfigureTestServices callbacks, so test registrations win. With minimal hosting, Program must be visible to the test project. The usual trick is public partial class Program; at the bottom of Program.cs.
UseSetting(key, value) adds a high-priority configuration value, so builder.Configuration.GetConnectionString("Orders") returns the container's string. If the app reads configuration in an unusual way, replace the registration in ConfigureTestServices instead. Since EF Core 8 and later, removing only DbContextOptions<T> is not always enough, because AddDbContext also registers configuration callbacks. Overriding configuration is usually simpler and more robust.
MsSqlBuilder().Build() creates a container definition. StartAsync pulls the image if needed, starts it on a random free host port and waits until SQL Server accepts connections. DisposeAsync stops and removes it. Ryuk, a reaper container, watches the test process and removes its containers if the process dies without cleaning up, so killed CI jobs don't leak containers. On CI you need Docker: GitHub-hosted Ubuntu runners have it, and for Azure DevOps use a Linux agent with Docker.
EnsureCreated builds the schema from the current model and skips migrations entirely, so a broken migration goes unnoticed. MigrateAsync runs the same migrations production will, which makes it a migration test for free.
Respawn's CreateAsync inspects the foreign keys once. ResetAsync deletes from child tables before parents. It's faster than dropping and migrating (milliseconds against seconds), and it keeps the schema and __EFMigrationsHistory. Combine it with a serial collection, or give each parallel class its own database so resets can't collide.
| Step | Typical |
|---|---|
| Image pull (first time on an agent) | 30-90 s; cache it |
| Container start | 5-15 s |
| Migrations | 1-3 s |
| Respawn reset | 20-50 ms |
| One API test | 10-100 ms |
MigrateAsync with EnsureCreatedAsync and add a migration with a bug. Notice which version catches it.A complete xUnit v3 test class: the API under test, a factory that owns a SQL Server container, migrations once, and Respawn before each test.
// ----- API project: Program.cs (code under test) -----
#nullable enable
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<OrdersDb>(o =>
o.UseSqlServer(builder.Configuration.GetConnectionString("Orders")));
var app = builder.Build();
app.MapPost("/orders", async (CreateOrder cmd, OrdersDb db, CancellationToken ct) =>
{
var order = new Order { Id = Guid.NewGuid(), CustomerEmail = cmd.CustomerEmail, Total = cmd.Total };
db.Orders.Add(order);
await db.SaveChangesAsync(ct);
return Results.Created($"/orders/{order.Id}", order);
});
app.MapGet("/orders/{id:guid}", async (Guid id, OrdersDb db, CancellationToken ct) =>
await db.Orders.FindAsync([id], ct) is { } o ? Results.Ok(o) : Results.NotFound());
app.Run();
public sealed record CreateOrder(string CustomerEmail, decimal Total);
public sealed class Order
{
public Guid Id { get; set; }
public required string CustomerEmail { get; set; }
public decimal Total { get; set; }
}
public sealed class OrdersDb(DbContextOptions<OrdersDb> options) : DbContext(options)
{
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<Order>().Property(o => o.Total).HasPrecision(18, 2);
}
public partial class Program; // makes Program visible to WebApplicationFactory
// ----- Test project -----
#nullable enable
using System.Net;
using System.Net.Http.Json;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Respawn;
using Testcontainers.MsSql;
using Xunit;
namespace Orders.Api.Tests;
public sealed class ApiFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
// Pin the image so CI and laptops run the same engine.
private readonly MsSqlContainer _sql = new MsSqlBuilder()
.WithImage("mcr.microsoft.com/mssql/server:2022-latest")
.Build();
private Respawner _respawner = null!;
public async ValueTask InitializeAsync()
{
await _sql.StartAsync();
// Touching Services builds the host, so ConfigureWebHost has already run.
using (var scope = Services.CreateScope())
{
var db = scope.ServiceProvider.GetRequiredService<OrdersDb>();
// EnsureCreated keeps this sample self-contained; real projects call MigrateAsync().
await db.Database.EnsureCreatedAsync();
}
_respawner = await Respawner.CreateAsync(_sql.GetConnectionString(), new RespawnerOptions
{
DbAdapter = DbAdapter.SqlServer,
TablesToIgnore = ["__EFMigrationsHistory"]
});
}
protected override void ConfigureWebHost(IWebHostBuilder builder) =>
// Highest-priority config value: the app's own AddDbContext uses it.
builder.UseSetting("ConnectionStrings:Orders", _sql.GetConnectionString());
public Task ResetDatabaseAsync() => _respawner.ResetAsync(_sql.GetConnectionString());
public override async ValueTask DisposeAsync()
{
await base.DisposeAsync(); // stop the host first...
await _sql.DisposeAsync(); // ...then remove the container
}
}
public sealed class OrdersEndpointTests(ApiFactory factory) : IClassFixture<ApiFactory>, IAsyncLifetime
{
private readonly HttpClient _client = factory.CreateClient();
public async ValueTask InitializeAsync() => await factory.ResetDatabaseAsync(); // clean rows per test
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
[Fact]
public async Task Created_order_can_be_read_back()
{
var ct = TestContext.Current.CancellationToken;
var post = await _client.PostAsJsonAsync("/orders", new CreateOrder("[email protected]", 42.50m), ct);
Assert.Equal(HttpStatusCode.Created, post.StatusCode);
var get = await _client.GetAsync(post.Headers.Location, ct);
var order = await get.Content.ReadFromJsonAsync<Order>(ct);
Assert.Equal(42.50m, order!.Total); // decimal(18,2) round-trips through real SQL Server
}
[Fact]
public async Task Unknown_order_returns_404()
{
var response = await _client.GetAsync($"/orders/{Guid.NewGuid()}", TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
For one shared container with a database per class, build the connection string with new SqlConnectionStringBuilder(sharedConnectionString) { InitialCatalog = $"orders_{Guid.NewGuid():N}" } and pass that to UseSetting. MigrateAsync then creates the database.
EnsureCreated in tests of an app that uses migrations. Why it is wrong: It skips the migrations, so a broken migration only fails on deployment. Instead: Call Database.MigrateAsync() once per fixture.ConfigureWebHost. Why it is wrong: It blocks synchronously and can run more than once, or before the port is known. Instead: Start it in InitializeAsync, then build the host.2022-latest or a specific CU.GetConnectionString().This combination is my default for API integration tests: it's the cheapest way to test the real pipeline, the real SQL and the real migrations together. In a code review I look for three things: migrations rather than EnsureCreated, a reset strategy that matches the parallelism, and a pinned image. Docker is the real cost. CI agents need it, and the first pull is slow, so cache the image or use a pre-warmed agent.
I measure fixture overhead from the TRX report (time per class) and widen the scope only when start-up dominates. If tests start failing intermittently after sharing a database, the cause is almost always two classes resetting or reading each other's rows.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Testcontainers SQL Server | Default for API and repository tests | Docker, 5-15 s start-up | Agents without Docker or nested virtualisation |
| SQLite in-memory | Fast checks of simple queries | Different SQL dialect, types and locking | SQL Server-specific features (temporal tables, JSON, rowversion) |
| EF Core in-memory provider | Almost never for data tests | False confidence | Anything involving constraints or transactions |
| Shared dev or test SQL database | Legacy suites | Shared state, flaky, slow | Parallel CI runs |
Wrap the resource in a fixture that implements IAsyncLifetime, so the container starts once in InitializeAsync and is removed in DisposeAsync. Then pick the sharing scope:
IClassFixture<T>: one instance per test class.ICollectionFixture<T> with [CollectionDefinition]: one instance for every class in the collection, and those classes run serially.[assembly: AssemblyFixture(typeof(T))]): one instance for the whole run, with tests still running in parallel, so the fixture must be thread-safe.Share the resource, not the state. Each test creates its own rows with unique keys, or you reset the database between tests with Respawn. Respawn is a small library that deletes data in foreign-key order and keeps the schema. The trade-off is that a wider scope gives a faster suite, but one test can leak data into another.
Choose the data strategy per test level:
Build edge cases in on purpose: Unicode names, boundary amounts, Australian daylight-saving changes. Never copy production PII into lower environments. Under the Privacy Act 1988 (APP 11), a test copy is still personal information you must protect, and a leak can be a notifiable data breach. The trade-off is that synthetic data takes effort to make realistic, but it removes a whole class of privacy risk.
How to tell it (STAR)
**S:** Our orders API's tests used the EF Core in-memory provider, and after a release production started returning 500s on duplicate order references. **T:** I needed to stop the errors and work out why a green suite missed them. **A:** I reproduced it against SQL Server in Docker and found the in-memory provider ignores unique indexes and our tests never ran migrations. I hotfixed the endpoint to return 409, then moved the suite to WebApplicationFactory with a Testcontainers SQL Server, real migrations and Respawn resets, and banned `UseInMemoryDatabase` in test projects. **R:** The new suite took [x] minutes longer in CI but found [n] more constraint bugs in the first month, and we had [no further] constraint-related incidents.
Last updated 23 Nov 2026.