testcontainers-dotnet
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.
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
appbuilder-action-scaffolder
IncludedCreate, implement, deploy, and debug Adobe Runtime actions with consistent layout, validation, and error handling. Use this skill whenever the user needs to add actions to an App Builder project, understand action structure (params, response format, web/raw actions), configure actions in the manifest, use App Builder SDKs (State, Files, Events, database), deploy and invoke actions via CLI, debug action issues, or implement patterns such as webhook receivers, custom event providers, journaling consumers, large payload redirects, action sequence pipelines, and Asset Compute workers. Also trigger when users mention serverless functions in Adobe context, action logging, IMS authentication for actions, or cron-style scheduled actions.
orchestrating-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. Use this skill when the user needs a multi-step Data Cloud pipeline, cross-phase troubleshooting, or data space and data kit management. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase sf data360 workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching phase-specific skill), the task is STDM/session tracing/parquet telemetry (use observing-agentforce), standard CRM SOQL (use querying-soql), or Apex implementation (use generating-apex).
github-project-automation
IncludedAutomate GitHub repository setup with CI/CD workflows, issue templates, Dependabot, and CodeQL security scanning. Includes 12 production-tested workflows and prevents 18 errors: YAML syntax, action pinning, and configuration. Use when: setting up GitHub Actions CI/CD, creating issue/PR templates, enabling Dependabot or CodeQL scanning, deploying to Cloudflare Workers, implementing matrix testing, or troubleshooting YAML indentation, action version pinning, secrets syntax, runner versions, or CodeQL configuration. Keywords: github actions, github workflow, ci/cd, issue templates, pull request templates, dependabot, codeql, security scanning, yaml syntax, github automation, repository setup, workflow templates, github actions matrix, secrets management, branch protection, codeowners, github projects, continuous integration, continuous deployment, workflow syntax error, action version pinning, runner version, github context, yaml indentation error
sf-datacloud
IncludedSalesforce Data Cloud product orchestrator for connect→prepare→harmonize→segment→act workflows. TRIGGER when: user needs a multi-step Data Cloud pipeline, asks to set up or troubleshoot Data Cloud across phases, manages data spaces or data kits, or wants a cross-phase `sf data360` workflow. DO NOT TRIGGER when: work is isolated to a single phase (use the matching sf-datacloud-* skill), the task is STDM/session tracing/parquet telemetry (use sf-ai-agentforce-observability), standard CRM SOQL (use sf-soql), or Apex implementation (use sf-apex).
fabric-cli
IncludedUse this skill for Fabric.so CLI workflows with the `fabric` terminal command: diagnose/install/login, search or browse a Fabric library, save notes/links/files, create folders, ask the Fabric AI assistant, manage tasks/workspaces, generate shell completion, check subscription usage, produce JSON output, and use Fabric as persistent agent memory. Do not use for Microsoft Fabric/Azure/Power BI `fab`, Daniel Miessler's Fabric framework, Python Fabric SSH, Fabric.js, or textile/fashion fabric.
lark
IncludedLark/Feishu CLI skills: lark-cli operations for docs, markdown, sheets, base, calendar, im, mail, task, okr, drive, wiki, slides, whiteboard, apps, approval, attendance, contact, vc, minutes, event. Use when the user needs to operate Lark/Feishu resources via lark-cli, send messages, manage documents, spreadsheets, calendars, tasks, OKRs, deploy web pages, or any Feishu/Lark workspace operations.