Community编程与开发github.com

testcontainers-integration-tests

使用 TestContainers for .NET 和 xUnit 编写集成测试。涵盖使用 Docker 容器中的真实数据库、消息队列和缓存进行基础设施测试,而非模拟。

testcontainers-integration-tests 是什么?

该技能专注于使用 TestContainers 库在 .NET 中编写集成测试,利用 Docker 容器启动真实的基础设施组件(如 SQL Server、PostgreSQL、MySQL、Redis 和 RabbitMQ),代替传统的模拟(mock)方式。它支持 xUnit 测试框架,并强调测试隔离、自动清理和 CI/CD 兼容性。用户可以通过创建基于容器的测试环境,验证真实的 SQL 查询、数据库约束、事务行为和消息队列集成,从而获得更高的测试信心。技能包含详细的代码示例、NuGet 包引用、常见问题解决方案以及 GitHub Actions 的 CI/CD 集成示例。

兼容平台~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/Aaronontheweb/dotnet-skills/tree/main/skills/testcontainers

Installed? Explore more 编程与开发 skills: steipete/bluebubbles, steipete/eightctl, steipete/blucli · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

使用 TestContainers 进行集成测试

何时使用此技能

在以下情况下使用此技能:

  • 编写需要真实基础设施(数据库、缓存、消息队列)的集成测试
  • 针对实际数据库测试数据访问层
  • 验证消息队列集成
  • 测试 Redis 缓存行为
  • 避免对基础设施组件使用模拟
  • 确保测试在与生产相似的环境中工作
  • 测试数据库迁移和架构变更

参考文件

核心原则

  1. 用真实基础设施代替模拟 - 在容器中使用实际数据库/服务,而非模拟
  2. 测试隔离 - 每个测试获取新的容器或新数据
  3. 自动清理 - TestContainers 处理容器生命周期和清理
  4. 快速启动 - 在适当情况下跨同一类中的测试重用容器
  5. CI/CD 兼容 - 在支持 Docker 的 CI 环境中无缝工作
  6. 端口随机化 - 容器使用随机端口避免冲突

为什么选择 TestContainers 而非模拟

模拟基础设施的问题

// 糟糕:模拟数据库
public class OrderRepositoryTests
{
    private readonly Mock<IDbConnection> _mockDb = new();

    [Fact]
    public async Task GetOrder_ReturnsOrder()
    {
        // 这不会测试真实的 SQL 行为、约束或性能
        _mockDb.Setup(db => db.QueryAsync<Order>(It.IsAny<string>()))
            .ReturnsAsync(new[] { new Order { Id = 1 } });

        var repo = new OrderRepository(_mockDb.Object);
        var order = await repo.GetOrderAsync(1);

        Assert.NotNull(order);
    }
}

问题:不测试实际的 SQL 查询,遗漏约束/索引,给出虚假信心,不捕获 SQL 语法错误。

更好:使用真实数据库的 TestContainers

// 良好:针对真实数据库进行测试
public class OrderRepositoryTests : IAsyncLifetime
{
    private readonly TestcontainersContainer _dbContainer;
    private IDbConnection _connection;

    public OrderRepositoryTests()
    {
        _dbContainer = new TestcontainersBuilder<TestcontainersContainer>()
            .WithImage("mcr.microsoft.com/mssql/server:2022-latest")
            .WithEnvironment("ACCEPT_EULA", "Y")
            .WithEnvironment("SA_PASSWORD", "Your_password123")
            .WithPortBinding(1433, true)
            .Build();
    }

    public async Task InitializeAsync()
    {
        await _dbContainer.StartAsync();
        var port = _dbContainer.GetMappedPublicPort(1433);
        var connectionString = $"Server=localhost,{port};Database=TestDb;User Id=sa;Password=Your_password123;TrustServerCertificate=true";
        _connection = new SqlConnection(connectionString);
        await _connection.OpenAsync();
        await RunMigrationsAsync(_connection);
    }

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

    [Fact]
    public async Task GetOrder_WithRealDatabase_ReturnsOrder()
    {
        await _connection.ExecuteAsync(
            "INSERT INTO Orders (Id, CustomerId, Total) VALUES (1, 'CUST1', 100.00)");

        var repo = new OrderRepository(_connection);
        var order = await repo.GetOrderAsync(1);

        Assert.NotNull(order);
        Assert.Equal("CUST1", order.CustomerId);
        Assert.Equal(100.00m, order.Total);
    }
}

有关完整的 SQL Server、PostgreSQL 和迁移测试示例,请参阅 database-patterns.md。

有关 Redis、RabbitMQ、多容器网络、容器重用和 Respawn 数据库重置模式的示例,请参阅 infrastructure-patterns.md。

必需的 NuGet 包

<ItemGroup>
  <PackageReference Include="Testcontainers" Version="*" />
  <PackageReference Include="xunit" Version="*" />
  <PackageReference Include="xunit.runner.visualstudio" Version="*" />

  <!-- 数据库特定包 -->
  <PackageReference Include="Microsoft.Data.SqlClient" Version="*" />
  <PackageReference Include="Npgsql" Version="*" /> <!-- 用于 PostgreSQL -->
  <PackageReference Include="MySqlConnector" Version="*" /> <!-- 用于 MySQL -->

  <!-- 其他基础设施 -->
  <PackageReference Include="StackExchange.Redis" Version="*" /> <!-- 用于 Redis -->
  <PackageReference Include="RabbitMQ.Client" Version="*" /> <!-- 用于 RabbitMQ -->
</ItemGroup>

最佳实践

  1. 始终使用 IAsyncLifetime - 正确的异步设置和拆卸
  2. 等待端口可用 - 使用 WaitStrategy 确保容器就绪
  3. 使用随机端口 - 让 TestContainers 自动分配端口
  4. 在测试之间清理数据 - 要么使用新容器,要么截断表
  5. 尽可能重用容器 - 比每个测试创建新容器更快
  6. 测试真实查询 - 不要只测试模拟;验证实际的 SQL 行为
  7. 验证约束 - 测试外键、唯一约束、索引
  8. 测试事务 - 验证回滚和提交行为
  9. 使用真实数据 - 使用类似生产的数据量进行测试
  10. 处理清理 - 始终在 DisposeAsync 中释放容器

常见问题及解决方案

容器启动超时

_container = new TestcontainersBuilder<TestcontainersContainer>()
    .WithImage("postgres:latest")
    .WithWaitStrategy(Wait.ForUnixContainer()
        .UntilPortIsAvailable(5432)
        .WithTimeout(TimeSpan.FromMinutes(2)))
    .Build();

端口已被占用

始终使用随机端口映射:

.WithPortBinding(5432, true) // true = 分配随机公共端口

容器未清理

确保正确释放:

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

测试在 CI 中失败但在本地通过

确保 CI 支持 Docker:

# GitHub Actions
runs-on: ubuntu-latest # 已预装 Docker

CI/CD 集成

GitHub Actions

name: Integration Tests

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v3

    - name: Setup .NET
      uses: actions/setup-dotnet@v3
      with:
        dotnet-version: 9.0.x

    - name: Run Integration Tests
      run: |
        dotnet test tests/YourApp.IntegrationTests \
          --filter Category=Integration \
          --logger trx

    - name: Cleanup Containers
      if: always()
      run: docker container prune -f

性能提示

  1. 重用容器 - 在集合中的测试之间共享固定设备
  2. 使用 Respawn - 无需重新创建容器即可重置数据
  3. 并行执行 - TestContainers 自动处理端口冲突
  4. 使用轻量级镜像 - Alpine 版本更小更快
  5. 缓存镜像 - Docker 会在本地缓存拉取的镜像

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

akka-hosting-actor-patterns

Patterns for building entity actors with Akka.Hosting - GenericChildPerEntityParent, message extractors, cluster sharding abstraction, akka-reminders, and ITimeProvider. Supports both local testing and clustered production modes.

akka-net-aspire-configuration

Configure Akka.NET with .NET Aspire for local development and production deployments. Covers actor system setup, clustering, persistence, Akka.Management integration, and Aspire orchestration patterns.

akka-net-best-practices

Critical Akka.NET best practices including EventStream vs DistributedPubSub, supervision strategies, error handling, Props vs DependencyResolver, work distribution patterns, and cluster/local mode abstractions for testability.

akka-net-management

Akka.Management for cluster bootstrapping, service discovery (Kubernetes, Azure, Config), health checks, and dynamic cluster formation without static seed nodes.

akka-net-testing-patterns

Write unit and integration tests for Akka.NET actors using modern Akka.Hosting.TestKit patterns. Covers dependency injection, TestProbes, persistence testing, and actor interaction verification. Includes guidance on when to use traditional TestKit.

api-design

Design stable, compatible public APIs using extend-only design principles. Manage API compatibility, wire compatibility, and versioning for NuGet packages and distributed systems.

aspire-configuration

Configure Aspire AppHost to emit explicit app config via environment variables; keep app code free of Aspire clients and service discovery.

aspire-integration-testing

Write integration tests using .NET Aspire

aspire-service-defaults

Create a shared ServiceDefaults project for Aspire applications. Centralizes OpenTelemetry, health checks, resilience, and service discovery configuration across all services.

crap-analysis

Analyze code coverage and CRAP (Change Risk Anti-Patterns) scores to identify high-risk code. Use OpenCover format with ReportGenerator for Risk Hotspots showing cyclomatic complexity and untested code paths.

csharp-concurrency-patterns

Choosing the right concurrency abstraction in .NET - from async/await for I/O to Channels for producer/consumer to Akka.NET for stateful entity management. Avoid locks and manual synchronization unless absolutely necessary.

database-performance

Database access patterns for performance. Separate read/write models, avoid N+1 queries, use AsNoTracking, apply row limits, and never do application-side joins. Works with EF Core and Dapper.

dependency-injection-patterns

Organize DI registrations using IServiceCollection extension methods. Group related services into composable Add* methods for clean Program.cs and reusable configuration in tests.

dotnet-devcert-trust

Diagnose and fix .NET HTTPS dev certificate trust issues on Linux. Covers the full certificate lifecycle from generation to system CA bundle inclusion, with distro-specific guidance for Ubuntu, Fedora, Arch, and WSL2.

dotnet-local-tools

Managing local .NET tools with dotnet-tools.json for consistent tooling across development environments and CI/CD pipelines.

dotnet-project-structure

Modern .NET project structure including .slnx solution format, Directory.Build.props, central package management, SourceLink, version management with RELEASE_NOTES.md, and SDK pinning with global.json.

dotnet-slopwatch

Use Slopwatch to detect LLM reward hacking in .NET code changes. Run after every code modification to catch disabled tests, suppressed warnings, empty catch blocks, and other shortcuts that mask real problems.

efcore-patterns

Entity Framework Core best practices including NoTracking by default, query splitting for navigation collections, migration management, dedicated migration services, and common pitfalls to avoid.

ilspy-decompile

Understand implementation details of .NET code by decompiling assemblies. Use when you want to see how a .NET API works internally, inspect NuGet package source, view framework implementation, or understand compiled .NET binaries.

mailpit-integration

Test email sending locally using Mailpit with .NET Aspire. Captures all outgoing emails without sending them. View rendered HTML, inspect headers, and verify delivery in integration tests.

相关技能