Community程式設計與開發github.com

TestContainers 整合測試

使用 TestContainers for .NET 與 xUnit 撰寫整合測試,涵蓋以 Docker 容器中的真實資料庫、訊息佇列和快取進行基礎設施測試,而非使用模擬物件。

TestContainers 整合測試 是什麼?

此技能專注於使用 TestContainers 函式庫在 .NET 環境中撰寫針對真實基礎設施的整合測試,而非依賴模擬物件 (mocks)。 它讓開發者能夠在 Docker 容器中啟動資料庫、快取(如 Redis)和訊息佇列(如 RabbitMQ)等服務,並在測試中使用它們。 支援的平台包括 GitHub Actions 等啟用 Docker 的 CI/CD 環境。 其核心優勢在於提供真實的行為驗證,例如捕捉 SQL 語法錯誤、確認資料庫約束和索引,以及測試交易行為,從而大幅提升測試的可信度。 該技能透過 xUnit 的 `IAsyncLifetime` 介面管理非同步的生命週期,並提供如容器重複使用和 Respawn 等模式來最佳化測試效能。

相容平台~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 快取行為
  • 避免對基礎設施元件使用模擬物件 (mocks)
  • 確保測試在類似生產環境中運作
  • 測試資料庫遷移和綱要變更

參考檔案

核心原則

  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);
    }
}

請參閱 database-patterns.md 以取得完整的 SQL Server、PostgreSQL 和遷移測試範例。

請參閱 infrastructure-patterns.md 以取得 Redis、RabbitMQ、多容器網路、容器重複使用和 Respawn 資料庫重置模式的範例。

必要的 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. 重複使用容器 - 在集合中的測試之間共用 Fixture
  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.

相關技能