Claude
Skills
Sign in
Back

testcontainers-dotnet

Included with Lifetime
$97 forever

A comprehensive guide for using Testcontainers for .NET (4.10.0+) to write reliable integration tests with Docker containers in .NET projects. Supports 65+ pre-configured modules for databases, message queues, cloud services, and more.

Cloud & DevOps

What this skill does


# Testcontainers for .NET Integration Testing

A comprehensive guide for using Testcontainers for .NET (4.10.0+) to write reliable integration tests with Docker containers in .NET projects.

## Description

This skill helps you write integration tests using Testcontainers for .NET, a .NET library that provides lightweight, throwaway instances of common databases, message queues, web browsers, or anything that can run in a Docker container.

**Key capabilities**:
- Use 65+ pre-configured modules for common services (databases, message queues, cloud services, etc.)
- Set up and manage Docker containers in .NET tests (xUnit, NUnit, MSTest)
- Configure networking, volumes, and environment variables
- Implement proper cleanup and resource management
- Debug and troubleshoot container issues

## When to Use This Skill

Use this skill when you need to:
- Write integration tests that require real services (databases, message queues, etc.)
- Test against multiple versions or configurations of dependencies
- Create reproducible test environments
- Avoid mocking external dependencies in integration tests
- Set up ephemeral test infrastructure

## Decision Rule (Recommended)

1. **If a pre-configured module exists for your service**, use the module.
2. **If no module exists**, use a generic container with `ContainerBuilder` **and always define an explicit wait strategy**.

## Prerequisites

- **Docker or Podman** installed and running
- **.NET 8.0+** (check project requirements; library supports .NET and .NET Standard)
- **Docker socket** accessible at standard locations (Docker Desktop on macOS/Windows, `/var/run/docker.sock` on Linux)
- **Test framework**: xUnit, NUnit, or MSTest

## Instructions

### Quick Start (Framework-Agnostic)

Use this when you want a minimal, reliable integration test setup without committing to xUnit/NUnit/MSTest patterns up front.

1. Create (or choose) a test project using your preferred test framework.
2. Add the Testcontainers module for your service (prefer modules over generic containers).
3. Add the client library for the service you will connect to.
4. Write a single test that:
    - starts the container
    - connects to the service and performs a small smoke operation
    - disposes the container (for example, via `await using`)
5. Run the test project.

```bash
# Example: PostgreSQL (module + client library)
dotnet add package Testcontainers.PostgreSql
dotnet add package Npgsql

# Run your tests (command varies by runner, but this works for most)
dotnet test
```

```csharp
// NuGet dependencies:
// - dotnet add package Npgsql
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3

using System;
using System.Threading;
using System.Threading.Tasks;
using Npgsql;
using Testcontainers.PostgreSql;

public sealed class PostgresSmokeTest
{
    // Note: Add your framework's test attribute (e.g., [Fact]/[Test]/[TestMethod]).
    public async Task CanQueryPostgres()
    {
        await using var postgres = new PostgreSqlBuilder("postgres:16-alpine").Build();
        await postgres.StartAsync(CancellationToken.None);

        await using var connection = new NpgsqlConnection(postgres.GetConnectionString());
        await connection.OpenAsync(CancellationToken.None);

        await using var command = new NpgsqlCommand("SELECT 1", connection);
        var result = await command.ExecuteScalarAsync(CancellationToken.None);

        if (!Equals(result, 1))
        {
            throw new InvalidOperationException($"Expected SELECT 1 to return 1. Actual: {result}");
        }
    }
}
```

### What I Need From You (Checklist)

When you ask for help, include these details so the generated test code matches your environment:

- **Test framework**: xUnit / NUnit / MSTest (and version if relevant)
- **.NET version**: e.g., net8.0
- **Container runtime**: Docker Desktop / Docker Engine / Podman (and OS)
- **Service under test**: PostgreSQL / Redis / SQL Server / Kafka / ...
- **Image + tag**: e.g., `postgres:16-alpine` (pin versions for CI stability)
- **How the test should connect**: host port mapping vs container-to-container network
- **Readiness signal**: HTTP endpoint, log line, command (if you know it)
- **Data setup**: schema/init scripts, seed data, migrations (and where they live)
- **Lifecycle**: per-test container vs shared fixture (performance vs isolation)
- **Parallelism/CI**: Will tests run in parallel? Any CI constraints/timeouts?

If you do not know an item, say so (the default recommendation is: module + explicit wait strategy + random host ports + dispose in teardown).

### 1. Installation & Setup

Add Testcontainers for .NET to your test project:

```bash
# Core library (required)
# For modules, the core library will be resolved through transitive dependencies.
dotnet add package Testcontainers

# For pre-configured modules (recommended)
# PostgreSQL
dotnet add package Testcontainers.PostgreSql

# SQL Server
dotnet add package Testcontainers.MsSql

# MySQL
dotnet add package Testcontainers.MySql

# MongoDB
dotnet add package Testcontainers.MongoDB

# Redis
dotnet add package Testcontainers.Redis

# Kafka
dotnet add package Testcontainers.Kafka

# RabbitMQ
dotnet add package Testcontainers.RabbitMq

# Elasticsearch
dotnet add package Testcontainers.Elasticsearch

# And many more...
```

**Verify Docker availability**:

Note: Testcontainers usually fails (throws) when **creating/starting containers or other resources** if no container runtime is reachable. The snippet below is a lightweight sanity check that helps you see what configuration Testcontainers resolves on the current machine.

```csharp
using DotNet.Testcontainers.Configurations;
using Xunit;

[Fact]
public void DockerIsAvailable()
{
    var testcontainersConfiguration = TestcontainersSettings.OS;
    Assert.NotNull(testcontainersConfiguration);
}
```

---

### 2. Using Pre-Configured Modules (Recommended Approach)

**Testcontainers for .NET provides 65+ pre-configured modules** that offer production-ready configurations, sensible defaults, and helper methods. **Always prefer modules over generic containers** when available.

#### Why Use Modules?

- **Sensible defaults**: Pre-configured ports, environment variables, and wait strategies
- **Connection helpers**: Built-in properties like `GetConnectionString()`, `GetBootstrapAddress()`
- **Specialized features**: Module-specific functionality (e.g., running scripts inside the container)
- **Automatic credentials**: Secure credential generation and management
- **Battle-tested**: Used in production by thousands of projects

#### Available Module Categories

**Databases (15+ modules)**:
- `Testcontainers.Cassandra`
- `Testcontainers.ClickHouse`
- `Testcontainers.CosmosDb`
- `Testcontainers.CouchDb`
- `Testcontainers.Db2`
- `Testcontainers.DynamoDb`
- `Testcontainers.InfluxDb`
- `Testcontainers.MariaDb`
- `Testcontainers.MongoDB`
- `Testcontainers.MsSql`
- `Testcontainers.MySql`
- `Testcontainers.Oracle`
- `Testcontainers.PostgreSql`
- `Testcontainers.Redis`

**Message Queues (5+ modules)**:
- `Testcontainers.Kafka`
- `Testcontainers.NATS`
- `Testcontainers.Pulsar`
- `Testcontainers.RabbitMq`
- `Testcontainers.Redpanda`

**Search & Storage (5+ modules)**:
- `Testcontainers.Azurite`
- `Testcontainers.Elasticsearch`
- `Testcontainers.LocalStack`
- `Testcontainers.Minio`
- `Testcontainers.Qdrant`

**Cloud & Infrastructure (5+ modules)**:
- `Testcontainers.Azurite` (Azure Storage)
- `Testcontainers.GCloud` (Google Cloud)
- `Testcontainers.LocalStack` (AWS services)
- `Testcontainers.Consul`
- `Testcontainers.Vault`

**Development Tools (10+ modules)**:
- `Testcontainers.WebDriver` (Selenium)
- `Testcontainers.Grafana`
- `Testcontainers.Keycloak`
- `Testcontainers.MockServer`
- `Testcontainers.Neo4j`

#### Basic Module Usage Pattern

```csharp
// NuGet dependencies:
// - dotnet add package Npgsql
// - dotnet add package Testcontainers.PostgreSql
// - dotnet add package xunit.v3

using Npgsql;

Related in Cloud & DevOps