Testcontainers for .NET: Real Infrastructure in xUnit and NUnit Tests

Testcontainers for .NET: Real Infrastructure in xUnit and NUnit Tests

Writing .NET integration tests against LocalDB or SQLite gives you false confidence. Your production code runs against PostgreSQL or SQL Server — why would your tests use something different? Testcontainers for .NET lets you spin up real Docker containers inside your test suite with zero manual setup.

Installation

Add the main package and any module you need:

dotnet add package Testcontainers
dotnet add package Testcontainers.PostgreSql
dotnet add package Testcontainers.MsSql
dotnet add package Testcontainers.Redis

You need Docker Desktop (or a compatible engine) running on your machine or CI agent.

PostgreSQL with xUnit

xUnit's IAsyncLifetime is the right hook for container lifecycle management. Implement it on your test class or a shared fixture:

using Testcontainers.PostgreSql;
using Npgsql;
using Xunit;

public class UserRepositoryTests : IAsyncLifetime
{
    private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .WithDatabase("testdb")
        .WithUsername("testuser")
        .WithPassword("testpass")
        .Build();

    public async Task InitializeAsync()
    {
        await _postgres.StartAsync();

        await using var conn = new NpgsqlConnection(_postgres.GetConnectionString());
        await conn.OpenAsync();

        await using var cmd = new NpgsqlCommand("""
            CREATE TABLE IF NOT EXISTS users (
                id   SERIAL PRIMARY KEY,
                name TEXT NOT NULL,
                email TEXT UNIQUE NOT NULL
            )
        """, conn);
        await cmd.ExecuteNonQueryAsync();
    }

    public async Task DisposeAsync()
    {
        await _postgres.DisposeAsync();
    }

    [Fact]
    public async Task InsertAndRetrieveUser()
    {
        await using var conn = new NpgsqlConnection(_postgres.GetConnectionString());
        await conn.OpenAsync();

        await using var insert = new NpgsqlCommand(
            "INSERT INTO users (name, email) VALUES (@name, @email) RETURNING id",
            conn
        );
        insert.Parameters.AddWithValue("name", "Alice");
        insert.Parameters.AddWithValue("email", "alice@example.com");

        var id = (int)await insert.ExecuteScalarAsync()!;

        await using var select = new NpgsqlCommand(
            "SELECT name FROM users WHERE id = @id", conn
        );
        select.Parameters.AddWithValue("id", id);

        var name = (string)await select.ExecuteScalarAsync()!;
        Assert.Equal("Alice", name);
    }
}

The container starts once before the test class runs and is destroyed after all tests in the class finish.

Sharing a Container Across Tests with Class Fixtures

Creating one container per test method is expensive. Use a shared CollectionFixture in xUnit to start a single container for an entire test collection:

public class PostgresFixture : IAsyncLifetime
{
    public PostgreSqlContainer Container { get; } = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .Build();

    public string ConnectionString => Container.GetConnectionString();

    public async Task InitializeAsync()
    {
        await Container.StartAsync();
        // Run migrations here
    }

    public async Task DisposeAsync() => await Container.DisposeAsync();
}

[CollectionDefinition("Postgres")]
public class PostgresCollection : ICollectionFixture<PostgresFixture> { }

[Collection("Postgres")]
public class OrderRepositoryTests
{
    private readonly string _connString;

    public OrderRepositoryTests(PostgresFixture fixture)
    {
        _connString = fixture.ConnectionString;
    }

    [Fact]
    public async Task CreateOrder_PersistsToDatabase()
    {
        // test uses _connString
    }
}

All classes tagged with [Collection("Postgres")] share the same container instance.

SQL Server with NUnit

NUnit uses [OneTimeSetUp] and [OneTimeTearDown] for the same pattern:

using Testcontainers.MsSql;
using Microsoft.Data.SqlClient;
using NUnit.Framework;

[TestFixture]
public class ProductRepositoryTests
{
    private MsSqlContainer _sqlServer = null!;
    private string _connectionString = null!;

    [OneTimeSetUp]
    public async Task SetUp()
    {
        _sqlServer = new MsSqlBuilder()
            .WithImage("mcr.microsoft.com/mssql/server:2022-latest")
            .Build();

        await _sqlServer.StartAsync();
        _connectionString = _sqlServer.GetConnectionString();

        await using var conn = new SqlConnection(_connectionString);
        await conn.OpenAsync();

        await using var cmd = new SqlCommand("""
            CREATE TABLE Products (
                Id    INT IDENTITY PRIMARY KEY,
                Name  NVARCHAR(200) NOT NULL,
                Price DECIMAL(10,2) NOT NULL
            )
        """, conn);
        await cmd.ExecuteNonQueryAsync();
    }

    [OneTimeTearDown]
    public async Task TearDown()
    {
        await _sqlServer.DisposeAsync();
    }

    [Test]
    public async Task InsertProduct_AssignedId()
    {
        await using var conn = new SqlConnection(_connectionString);
        await conn.OpenAsync();

        await using var cmd = new SqlCommand(
            "INSERT INTO Products (Name, Price) OUTPUT INSERTED.Id VALUES (@name, @price)",
            conn
        );
        cmd.Parameters.AddWithValue("@name", "Widget");
        cmd.Parameters.AddWithValue("@price", 9.99m);

        var id = (int)await cmd.ExecuteScalarAsync()!;
        Assert.That(id, Is.GreaterThan(0));
    }
}

ASP.NET Core Integration with WebApplicationFactory

Testcontainers pairs naturally with WebApplicationFactory<T> to replace your real database with a containerised one during API tests:

public class ApiIntegrationTests : IClassFixture<CustomWebApplicationFactory>
{
    private readonly HttpClient _client;

    public ApiIntegrationTests(CustomWebApplicationFactory factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task GetUsers_ReturnsOk()
    {
        var response = await _client.GetAsync("/api/users");
        response.EnsureSuccessStatusCode();
    }
}

public class CustomWebApplicationFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .Build();

    public async Task InitializeAsync() => await _postgres.StartAsync();

    public new async Task DisposeAsync() => await _postgres.DisposeAsync();

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            // Remove existing DbContext registration
            var descriptor = services.SingleOrDefault(
                d => d.ServiceType == typeof(DbContextOptions<AppDbContext>));
            if (descriptor != null) services.Remove(descriptor);

            // Register the container's connection string
            services.AddDbContext<AppDbContext>(opts =>
                opts.UseNpgsql(_postgres.GetConnectionString()));
        });
    }
}

Your entire API stack runs in-process with a real database — migrations, EF Core relationships, and all.

Redis for Caching Tests

using Testcontainers.Redis;
using StackExchange.Redis;

public class CacheServiceTests : IAsyncLifetime
{
    private readonly RedisContainer _redis = new RedisBuilder()
        .WithImage("redis:7-alpine")
        .Build();

    private IConnectionMultiplexer _connection = null!;

    public async Task InitializeAsync()
    {
        await _redis.StartAsync();
        _connection = await ConnectionMultiplexer.ConnectAsync(_redis.GetConnectionString());
    }

    public async Task DisposeAsync()
    {
        await _connection.DisposeAsync();
        await _redis.DisposeAsync();
    }

    [Fact]
    public async Task Set_And_Get_Value()
    {
        var db = _connection.GetDatabase();
        await db.StringSetAsync("key", "value", TimeSpan.FromMinutes(5));

        var result = await db.StringGetAsync("key");
        Assert.Equal("value", result.ToString());
    }
}

CI Configuration

GitHub Actions runs Docker by default on ubuntu-latest:

name: Integration Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with:
          dotnet-version: "8.0.x"
      - run: dotnet test --configuration Release

No Docker Compose, no external services — the containers are created and destroyed inside the test runner process.

Wrapping Up

Testcontainers for .NET makes integration tests reliable without the ceremony of maintaining a separate Docker Compose file or a shared dev database. Your tests own their infrastructure, which means parallel runs, no state leakage, and the same behaviour on every developer's machine and in CI.

To catch regressions the moment they reach staging or production, pair your test suite with HelpMeTest — 24/7 monitoring that runs your critical flows continuously so issues surface before your users see them.

Read more

Start now free