Covers Testcontainers for .NET modules for SQL Server and Redis, IAsyncLifetime fixtures, sharing containers per class or collection, container reuse, resetting data with Respawn, wait strategies, Ryuk clean-up, and running in GitHub Actions and Azure Pipelines.
Testcontainers for .NET starts real Docker containers from test code and gives you their connection details. With Testcontainers.MsSql you build new MsSqlBuilder().WithImage("mcr.microsoft.com/mssql/server:2022-latest").Build(), await StartAsync() in an IAsyncLifetime fixture, and pass GetConnectionString() to EF Core. Testcontainers.Redis works the same way.
To keep it fast:
WithReuse(true) locally to skip start-up between runs.In CI you need a Docker host: Linux GitHub Actions runners and Microsoft-hosted Ubuntu agents have one. The trade-off is seconds of start-up and a Docker dependency for tests that behave like production, unlike the in-memory provider.
"Testcontainers is a library that talks to the Docker API from my test code. I say 'give me SQL Server 2022', it pulls the image, starts the container on a random free port, waits until the database actually accepts connections, and hands me a connection string. When the test run ends, a small sidecar container called Ryuk removes everything, even if the test process crashed. That gives me real SQL Server behaviour: real T-SQL translation, constraints, transactions, isolation levels, rowversion, without a shared test database that someone else is also writing to.
The important part is lifetime. A SQL Server container takes roughly 10 to 20 seconds to start, so I never start one per test. I wrap it in an
IAsyncLifetimefixture, share it across a test class or an xUnit collection, run migrations once inInitializeAsync, and between tests I reset data with Respawn, which deletes rows in foreign-key order in tens of milliseconds. Redis is the same pattern and starts in about a second. Locally I turn onWithReuse(true)so the container survives between runs and my inner loop stays under a few seconds. For example, at [company] we [replaced a shared dev database for tests]; flaky failures from other people's data [went to zero] and the suite took [N] minutes.In CI the only requirement is a Docker host. Linux GitHub Actions runners and Microsoft-hosted Ubuntu agents in Azure Pipelines have Docker installed, so it just works; Windows agents are the usual trap. I pin image tags so a new SQL Server CU doesn't change behaviour under me. The mistake I see is people avoiding real databases because they think it's slow; done properly it's a one-off 15 seconds, and it catches the bugs the in-memory provider hides."
| Piece | Purpose |
|---|---|
MsSqlBuilder, RedisBuilder, PostgreSqlBuilder |
Modules with sensible defaults and wait strategies |
ContainerBuilder |
Generic container for anything else (WireMock, Azurite, Service Bus emulator) |
StartAsync / DisposeAsync |
Start and stop; put them in IAsyncLifetime |
GetConnectionString() |
Includes the mapped random port |
| Wait strategies | Block until a port, log line or command succeeds |
| Ryuk (resource reaper) | Removes containers when the session ends |
WithReuse(true) |
Keep and reuse a container across runs (local only) |
| Scope | How | Trade-off |
|---|---|---|
| Per test | Fixture in constructor | Correct but far too slow |
| Per class | IClassFixture<T> |
Classes still run in parallel, each with its own container |
| Per collection | ICollectionFixture<T> |
One container, classes in it run serially |
| Per assembly | xUnit v3 assembly fixture | Fewest containers; data isolation matters most |
A payments team replaced 300 EF Core in-memory tests with Testcontainers SQL Server tests. Start-up added 14 seconds per CI run and the suite went from 45 seconds to 95 seconds, but in the first month the new tests caught a unique-constraint race, a query that EF could not translate and a decimal precision truncation, all of which had previously reached the test environment.
Checks practical experience running real infrastructure in tests and the judgement to keep it fast and reliable.
Green flags
Red flags
test process
| Docker Engine API (unix socket / named pipe / TCP)
v
Docker daemon ---> pulls image ---> starts container
| | port 1433 -> random host port 49xxx
| v
| wait strategy: "SQL Server is ready" / sqlcmd succeeds
v
Ryuk sidecar: watches the session, removes labelled containers when the process exits
Testcontainers uses the Docker.DotNet client, so it works wherever there is a Docker-compatible API: Docker Desktop, Rancher Desktop, Podman with the Docker socket, or a remote daemon via DOCKER_HOST. Testcontainers for .NET is MIT licensed.
Each container maps its internal port to a random free host port. That is what lets parallel test classes, or parallel CI jobs on one agent, run side by side. Never hard-code localhost,1433; always use GetConnectionString() or GetMappedPublicPort().
A started container is not a ready database. Modules include a wait strategy: SQL Server waits until a query succeeds, Redis until the port accepts PING. For a custom container, use Wait.ForUnixContainer().UntilMessageIsLogged("...") or UntilHttpRequestIsSucceeded(...). Missing wait strategies are the top cause of flaky first tests.
Options, fastest first:
DELETE in the right order; typically 20 to 100 ms.Pulling mssql/server (about 1.5 GB) is the slowest part on a fresh agent. Cache it with a pre-pull step or a self-hosted agent. WithReuse(true) hashes the container configuration and reuses a running container with the same hash; Ryuk does not remove reused containers, so it suits local loops, not CI.
The container runs SQL Server on Linux, which supports almost everything an application uses (not features like some Windows authentication scenarios). Developer edition semantics apply, which licenses non-production use. Azure SQL differs slightly (for example, RCSI is on by default in Azure SQL Database), so set READ_COMMITTED_SNAPSHOT ON in the container if production relies on it.
MsSqlContainer in a fixture and time StartAsync on a cold and a warm image cache.WithReuse(true), run the suite twice and compare timings; then check docker ps.ubuntu-latest job with no extra setup.A shared SQL Server and Redis fixture, Respawn between tests, and a repository test, all with xUnit v3:
// CustomerRepository.cs (code under test)
using Microsoft.EntityFrameworkCore;
namespace Crm.Data;
public sealed class Customer
{
public int Id { get; set; }
public required string Email { get; set; }
}
public sealed class CrmDbContext(DbContextOptions<CrmDbContext> options) : DbContext(options)
{
public DbSet<Customer> Customers => Set<Customer>();
protected override void OnModelCreating(ModelBuilder b) =>
b.Entity<Customer>().HasIndex(c => c.Email).IsUnique();
}
public sealed class CustomerRepository(CrmDbContext db)
{
public async Task<int> AddAsync(string email, CancellationToken ct)
{
var customer = new Customer { Email = email };
db.Customers.Add(customer);
await db.SaveChangesAsync(ct);
return customer.Id;
}
}
// DatabaseFixture.cs + CustomerRepositoryTests.cs
using Crm.Data;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Respawn;
using Testcontainers.MsSql;
using Testcontainers.Redis;
using Xunit;
namespace Crm.Data.Tests;
public sealed class DatabaseFixture : IAsyncLifetime
{
// Pin the image so a new CU can't change behaviour silently.
private readonly MsSqlContainer _sql = new MsSqlBuilder()
.WithImage("mcr.microsoft.com/mssql/server:2022-CU16-ubuntu-22.04")
.Build();
private readonly RedisContainer _redis = new RedisBuilder().WithImage("redis:7.4-alpine").Build();
private Respawner _respawner = null!;
public string SqlConnectionString => _sql.GetConnectionString();
public string RedisConnectionString => _redis.GetConnectionString();
public async ValueTask InitializeAsync()
{
// Start both in parallel: SQL Server dominates (~10-20 s), Redis ~1 s.
await Task.WhenAll(_sql.StartAsync(), _redis.StartAsync());
await using var db = CreateContext();
await db.Database.MigrateAsync(); // or EnsureCreatedAsync() if there are no migrations
await using var conn = new SqlConnection(SqlConnectionString);
await conn.OpenAsync();
_respawner = await Respawner.CreateAsync(conn, new RespawnerOptions { DbAdapter = DbAdapter.SqlServer });
}
public CrmDbContext CreateContext() =>
new(new DbContextOptionsBuilder<CrmDbContext>().UseSqlServer(SqlConnectionString).Options);
public async Task ResetAsync()
{
await using var conn = new SqlConnection(SqlConnectionString);
await conn.OpenAsync();
await _respawner.ResetAsync(conn); // deletes rows in FK order, keeps schema
}
public async ValueTask DisposeAsync()
{
await _sql.DisposeAsync();
await _redis.DisposeAsync();
}
}
[CollectionDefinition(nameof(DatabaseCollection))]
public sealed class DatabaseCollection : ICollectionFixture<DatabaseFixture>;
[Collection(nameof(DatabaseCollection))]
public sealed class CustomerRepositoryTests(DatabaseFixture fx) : IAsyncLifetime
{
public async ValueTask InitializeAsync() => await fx.ResetAsync();
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
[Fact]
public async Task Adds_customer_and_returns_generated_id()
{
await using var db = fx.CreateContext();
var id = await new CustomerRepository(db).AddAsync("[email protected]", TestContext.Current.CancellationToken);
Assert.True(id > 0);
}
[Fact]
public async Task Duplicate_email_is_rejected_by_the_real_unique_index()
{
await using var db = fx.CreateContext();
var repo = new CustomerRepository(db);
await repo.AddAsync("[email protected]", TestContext.Current.CancellationToken);
await using var db2 = fx.CreateContext();
// The EF in-memory provider would NOT enforce this index.
await Assert.ThrowsAsync<DbUpdateException>(
() => new CustomerRepository(db2).AddAsync("[email protected]", TestContext.Current.CancellationToken));
}
}
# .github/workflows/ci.yml: ubuntu runners already have Docker, nothing extra needed
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with: { dotnet-version: '10.0.x' }
- run: docker pull mcr.microsoft.com/mssql/server:2022-CU16-ubuntu-22.04 # optional warm-up
- run: dotnet test --configuration Release
localhost,1433. Why it is wrong: The host port is random; parallel runs collide. Instead: Use GetConnectionString() or GetMappedPublicPort().:latest image tags. Why it is wrong: A new SQL Server or Redis release changes behaviour and breaks tests on an unrelated PR. Instead: Pin a specific tag and update deliberately.UntilMessageIsLogged / UntilPortIsAvailable.WithReuse(true) in CI. Why it is wrong: Ryuk doesn't clean reused containers, so self-hosted agents accumulate them and state leaks between builds. Instead: Reuse locally only.ALTER DATABASE ... SET READ_COMMITTED_SNAPSHOT ON).Testcontainers removed the main excuse for not testing against a real database. The design work is in isolation and speed: one container per collection or assembly, data reset with Respawn, image pre-pulled on CI. Done that way a few hundred database tests run in one to two minutes, which is well worth the bugs they catch.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Testcontainers SQL Server | EF Core and SQL behaviour, constraints, concurrency | Docker host, ~15 s start, 1.5 GB image | Pure domain logic |
| SQLite in-memory | Fast relational checks with no Docker | Different SQL dialect and types | SQL Server-specific features |
| EF Core in-memory provider | Almost never for data access tests | Hides translation and constraint bugs | Anything that touches queries |
| Shared test database | Legacy setups only | Cross-test and cross-team interference | New projects |
Track container start time and total suite time in CI; if start-up dominates, move to assembly-level sharing or pre-pulled images.
Not for anything that tests data access. The EF Core in-memory provider runs LINQ against in-memory collections; it never generates SQL, so untranslatable queries, SQL Server collation and case-sensitivity, null semantics, constraints, foreign keys, unique indexes and transactions all behave differently, and tests pass that would fail on SQL Server. Microsoft's EF Core testing docs discourage it for testing. It can still serve quick tests of application logic that merely uses a DbContext, where speed matters more than fidelity. For integration tests use SQL Server in Testcontainers (or SQLite in-memory as a compromise with a different dialect), and reset state with Respawn or rolled-back transactions.
Add the Testcontainers.MsSql package. In an xUnit collection fixture that implements IAsyncLifetime, build an MsSqlContainer with a pinned image, await StartAsync() in InitializeAsync, and await DisposeAsync() in teardown (Testcontainers' Ryuk reaper also removes orphaned containers if a CI job dies). Pass GetConnectionString() to a WebApplicationFactory by overriding configuration, apply EF Core migrations once, and reset data between tests with Respawn. If the container fails to start (for example the CI agent has no Docker), fail fast with a clear message rather than skipping. Each run gets a clean, real SQL Server, catching translation and constraint bugs that the in-memory provider hides.
How to tell it (STAR)
**S:** At [company] our integration tests ran against a shared test database, and about [one in six] builds failed randomly. **T:** I was asked to make the pipeline trustworthy again. **A:** I traced the failures to tests colliding with other runs and with each other, moved the suite to a Testcontainers SQL Server shared per collection, reset data with Respawn before each test and pinned the image to production's CU. **R:** Random failures dropped from [~17%] to under [1%], the suite ran in [3 minutes], and we deleted the shared database's CI credentials.
Last updated 23 Nov 2026.