📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you use Testcontainers for .NET to run tests against a real SQL Server and Redis? Show the fixture, explain how you keep the tests fast (sharing, reuse, resetting data) and what you need to run them in CI.

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.

Mid-Level Coding Intermediate ci-cd integration-testing redis sql-server testcontainers testing

🎯 Key points

  • Testcontainers.MsSql / Testcontainers.Redis modules start real containers via the Docker API
  • Start in IAsyncLifetime.InitializeAsync; GetConnectionString() gives a random host port
  • Apply EF Core schema migrations (MigrateAsync) once per shared container, not per test
  • Share one container per class or collection; never one per test
  • Reset data between tests with Respawn (or unique keys) instead of new containers; parallel classes need their own data or their own container
  • Module wait strategies block until the service accepts connections, preventing flaky first tests
  • Ryuk (resource reaper) removes containers even if the test process crashes; WithReuse(true) keeps them for fast local loops only
  • Pin image tags; CI needs a Docker host (Linux GitHub Actions and Azure Pipelines hosted agents have one)

⏱ 30-second answer

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:

  • Share one container per class or collection, and apply migrations once.
  • Reset data between tests with Respawn instead of new containers.
  • Use 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 IAsyncLifetime fixture, share it across a test class or an xUnit collection, run migrations once in InitializeAsync, 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 on WithReuse(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."


The building blocks

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)

Sharing options

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

Production example

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.

🔍 What the interviewer is checking

Checks practical experience running real infrastructure in tests and the judgement to keep it fast and reliable.

Green flags

  • Uses IAsyncLifetime fixtures and shares containers sensibly
  • Resets data with Respawn or unique keys, not new containers
  • Knows about random ports, wait strategies and pinned images
  • Knows what CI needs (Linux agent with Docker)

Red flags

  • One container per test or hard-coded ports
  • Prefers the in-memory provider without understanding what it hides
  • Hasn't thought about CI at all

📚 Learn in depth

1. How Testcontainers works

 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.

2. Random ports and isolation

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().

3. Wait strategies

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.

4. Resetting data

Options, fastest first:

  1. Unique data per test (new customer id): no reset at all, works with parallel tests.
  2. Respawn: inspects foreign keys once, then issues DELETE in the right order; typically 20 to 100 ms.
  3. Transaction per test, rolled back: fast, but breaks if the code under test opens its own transaction or uses a different connection.
  4. Database snapshot or new database per class: strong isolation, slower.

5. Reuse and image pulls

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.

6. SQL Server specifics

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.

Try it yourself

  1. Start an MsSqlContainer in a fixture and time StartAsync on a cold and a warm image cache.
  2. Write a test that relies on a unique index violation and watch it pass on SQL Server but not on the in-memory provider.
  3. Add Respawn and measure reset time across 50 tests.
  4. Enable WithReuse(true), run the suite twice and compare timings; then check docker ps.
  5. Run the same tests in a GitHub Actions ubuntu-latest job with no extra setup.

💻 Code

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

⚠ Common mistakes

  • Mistake: Starting a container per test. Why it is wrong: 10 to 20 seconds each makes the suite unusable. Instead: Share per class, collection or assembly and reset data.
  • Mistake: Hard-coding localhost,1433. Why it is wrong: The host port is random; parallel runs collide. Instead: Use GetConnectionString() or GetMappedPublicPort().
  • Mistake: Using :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.
  • Mistake: No wait strategy on a custom container. Why it is wrong: The first test connects before the service is ready and fails intermittently. Instead: Use module defaults or UntilMessageIsLogged / UntilPortIsAvailable.
  • Mistake: Relying on test order instead of resetting data. Why it is wrong: Tests pass alone and fail together, or vice versa. Instead: Respawn before each test, or unique keys per test.
  • Mistake: Enabling 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.
  • Mistake: Running on Windows CI agents without Linux container support. Why it is wrong: Linux images can't start, so the job fails or hangs. Instead: Use Linux agents for container-based tests.
  • Mistake: Assuming the container matches Azure SQL exactly. Why it is wrong: Defaults such as RCSI differ. Instead: Configure the container like production (ALTER DATABASE ... SET READ_COMMITTED_SNAPSHOT ON).

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate compares Testcontainers with the in-memory provider. Why: Checks understanding of what the in-memory provider hides.
    How to answer

    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.

  2. When: Candidate mentions running the tests in a pipeline. Why: Checks CI setup details for container-based tests.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Integration tests flaky on a shared database, moved to Testcontainers
Situation
A CRM API with [~400] integration tests running against a shared Azure SQL test database used by [three] teams and every CI build. Release cadence was [weekly].
Signals
[15-20%] of CI runs failed with duplicate key or 'expected 1 row, got 3' errors that passed on re-run. Developers re-ran builds by habit; the CI retry rate was visible in the pipeline analytics.
Investigation
Grouped failures in the CI test reports: almost all were in data-dependent assertions. Correlated failure times with other teams' builds and found overlap. Confirmed tests relied on rows left by earlier tests and on other runs not touching the same tables.
Resolution
Short term, serialised the integration stage. Long term, moved to a Testcontainers SQL Server collection fixture with migrations applied once and Respawn before each test, and pinned the SQL Server image to the CU production used.
Prevention
Integration tests can only use the fixture's connection string (the shared database credentials were removed from CI); a docker pull warm-up step; a dashboard of flaky-test rate from the test reports.

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.

↩ Usually asked after

More in .NET Testing Tools

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me