A specialized skill for containerized database testing using Testcontainers. Use when you need to test real database behavior with SQL Server/PostgreSQL/MySQL containers or when testing EF Core/Dapper. Covers container startup, database migrations, test isolation, container sharing, lifecycle management, automatic cleanup, and version consistency strategies. Keywords: testcontainers, container testing, database testing, MsSqlContainer, PostgreSqlContainer, MySqlContainer, EF Core testing, Dapper testing, Testcontainers.MsSql, Testcontainers.PostgreSql, GetConnectionString, IAsyncLifetime, CollectionFixture
在選擇測試策略前,必須了解 EF Core InMemory 資料庫的重大限制:
SaveChanges() 後資料立即儲存,無法進行 RollbackInMemory 模式無法測試:預存程序、Triggers、Views、外鍵約束、檢查約束、資料類型精確度、Concurrency Tokens 等。
結論:當需要驗證複雜交易邏輯、並發處理、資料庫特定行為時,應使用 Testcontainers 進行整合測試。
Testcontainers 是一個測試函式庫,提供輕量好用的 API 來啟動 Docker 容器,專門用於整合測試。
<ItemGroup>
<!-- 測試框架 -->
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.3.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5" />
<PackageReference Include="AwesomeAssertions" Version="9.4.0" />
<!-- Testcontainers 核心套件 -->
<PackageReference Include="Testcontainers" Version="4.11.0" />
<!-- 資料庫容器 -->
<PackageReference Include="Testcontainers.PostgreSql" Version="4.11.0" />
<PackageReference Include="Testcontainers.MsSql" Version="4.11.0" />
<!-- Entity Framework Core -->
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="9.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="9.0.0" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="9.0.0" />
<!-- Dapper (可選) -->
<PackageReference Include="Dapper" Version="2.1.72" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="7.0.0" />
</ItemGroup>
重要:使用
Microsoft.Data.SqlClient而非舊版System.Data.SqlClient,提供更好的效能與安全性。
使用 IAsyncLifetime 管理容器生命週期,在 InitializeAsync 中啟動容器並建立 DbContext,在 DisposeAsync 中釋放資源。支援 PostgreSQL(PostgreSqlBuilder)和 SQL Server(MsSqlBuilder)。
完整程式碼範例請參考 references/container-basics.md
在大型專案中,每個測試類別都建立新容器會遇到嚴重的效能瓶頸。Collection Fixture 讓所有測試類別共享同一個容器,測試執行時間可減少約 67%。
包含 SQL 腳本外部化策略(將 SQL 檔案從 C# 程式碼分離)與 Wait Strategy 最佳實務。
完整 Collection Fixture 實作、SQL 腳本外部化與 Wait Strategy 範例請參考 references/collection-fixture-and-scripts.md
涵蓋 Include/ThenInclude 多層關聯查詢、AsSplitQuery 避免笛卡兒積、N+1 查詢問題驗證、AsNoTracking 唯讀查詢最佳化等完整測試範例。
完整程式碼範例請參考 references/orm-advanced-testing.md
涵蓋基本 CRUD 測試類別設置、QueryMultiple 一對多關聯處理、DynamicParameters 動態查詢建構等完整測試範例。
完整程式碼範例請參考 references/orm-advanced-testing.md
IProductRepository:基礎 CRUD 操作介面(GetAll、GetById、Add、Update、Delete)IProductByEFCoreRepository:EF Core 特有進階功能(SplitQuery、BatchUpdate、NoTracking)IProductByDapperRepository:Dapper 特有進階功能(多表查詢、動態參數、預存程序)# 檢查連接埠是否被佔用
netstat -an | findstr :5432
# 清理未使用的映像檔
docker system prune -a
Testcontainers 4.8.0 起,預設等待策略改為等待容器進入 Running 狀態。若容器未能正常啟動,會拋出此例外。常見原因:映像檔名稱錯誤、Docker 資源不足、連接埠衝突。
在 Dispose 中按照外鍵約束順序清理資料(OrderItems → Orders → Products → Categories)。
本技能內容提煉自「老派軟體工程師的測試修練 - 30 天挑戰」系列文章:
Day 20 - Testcontainers 初探:使用 Docker 架設測試環境
Day 21 - Testcontainers 整合測試:MSSQL + EF Core 以及 Dapper 基礎應用
dotnet-testing-advanced-testcontainers-nosql - NoSQL 容器測試(MongoDB、Redis)dotnet-testing-advanced-webapi-integration-testing - 完整 WebAPI 整合測試dotnet-testing-advanced-aspnet-integration-testing - ASP.NET Core 基礎整合測試dotnet-testing-advanced-xunit-upgrade-guide - xUnit v3 升級指南(含 Testcontainers.XunitV3 整合說明)xUnit v3 使用者注意:搭配 xUnit v3 時,可使用
Testcontainers.XunitV3(4.9.0)套件自動管理容器生命週期,取代手動實作IAsyncLifetime。
npx skills add kevintsengtw/dotnet 测试 - 进阶 Testcontainers 数据库下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer