Skip to main content
dotnet-testing-advanced-testcontainers-nosql Testcontainers NoSQL 整合測試完整指南。當需要對 MongoDB 或 Redis 進行容器化整合測試時使用。涵蓋 MongoDB 文件操作、Redis 五種資料結構、Collection Fixture 模式。包含 BSON 序列化、索引效能測試、資料隔離策略與容器生命週期管理。
Make sure to use this skill whenever the user mentions Testcontainers MongoDB, Testcontainers Redis, NoSQL integration test, BSON serialization, or Redis data structure testing, even if they don't explicitly ask for NoSQL container testing.
Keywords: testcontainers mongodb, testcontainers redis, mongodb integration test, redis integration test, nosql testing, MongoDbContainer, RedisContainer, IMongoDatabase, IConnectionMultiplexer, BSON serialization, BsonDocument, 文件模型測試, 快取測試, Collection Fixture
Aller à l'installation Skills Marketplace Découvrez et explorez les compétences IA créées par la communauté.
Installer avec Codex ou Claude Copiez ce prompt, collez-le dans Codex, Claude ou un autre assistant, puis laissez-le vérifier la page du skill et l'installer pour vous.
Copier le promptAfficher les détails du prompt Une commande directe contourne le prompt de vérification. Examinez la source avant de l'exécuter.
npx skills add https://github.com/kevintsengtw/dotnet-testing-agent-skills --skill dotnet-testing-advanced-testcontainers-nosqlLa commande reste sur une seule ligne. Faites défiler horizontalement pour la vérifier avant de la copier.
Vous préférez une copie locale ? Téléchargez les fichiers actuellement disponibles dans SkillsMP.
Télécharger Zip Téléchargement... Explorateur de fichiers
8 fichiers Métiers associés SOC
Basé sur la classification professionnelle SOC
dotnet-testing-advanced-aspire-testing .NET Aspire Testing 整合測試框架完整指南。當需要測試 .NET Aspire 分散式應用程式、設定 AppHost 測試或從 Testcontainers 遷移至 Aspire 測試時使用。涵蓋 DistributedApplicationTestingBuilder、容器生命週期管理、多服務編排、Respawn 配置與時間可測試性設計。
Make sure to use this skill whenever the user mentions .NET Aspire, AppHost testing, DistributedApplicationTestingBuilder, cloud-native testing, or migrating from Testcontainers to Aspire, even if they don't explicitly ask for Aspire testing guidance.
Keywords: aspire testing, .NET Aspire, DistributedApplicationTestingBuilder, AppHost testing, 分散式測試, AspireAppFixture, IAsyncLifetime, ContainerLifetime.Session, 雲原生測試, 多服務整合, Aspire.Hosting.Testing, Respawn
dotnet-testing-advanced-aspnet-integration-testing ASP.NET Core 整合測試的專門技能。當需要測試 Web API 端點、HTTP 請求/回應、中介軟體、依賴注入時使用。涵蓋 WebApplicationFactory、TestServer、HttpClient 測試、記憶體資料庫配置等。
Make sure to use this skill whenever the user mentions ASP.NET Core integration testing, WebApplicationFactory, TestServer, HTTP endpoint testing, or middleware testing, even if they don't explicitly ask for integration testing guidance.
Keywords: integration testing, 整合測試, web api testing, WebApplicationFactory, TestServer, HttpClient testing, controller testing, endpoint testing, 端點測試, RESTful API testing, Microsoft.AspNetCore.Mvc.Testing, CreateClient, ConfigureWebHost, AwesomeAssertions.Web, Be200Ok, Be404NotFound, middleware testing, 中介軟體測試, dependency injection testing
.NET 進階測試技能總覽與引導中心。當使用者詢問「整合測試」、「API 測試」、「容器化測試」、「微服務測試」、「測試框架遷移」、「Testcontainers」、「Aspire 測試」等進階測試需求時觸發。會根據具體需求推薦適合的子技能組合,涵蓋整合測試、Testcontainers、Aspire 測試、框架升級等 8 個進階技能。
Make sure to use this skill whenever the user mentions integration testing, API testing, Testcontainers, .NET Aspire testing, WebApplicationFactory, or xUnit/TUnit migration, even if they don't explicitly ask for advanced testing guidance.
Keywords: integration testing, 整合測試, API testing, advanced testing, 進階測試, testcontainers, aspire testing, WebApplicationFactory, TestServer, database test, 資料庫測試, EF Core test, MongoDB test, Redis test, Docker test, 容器測試, microservice test, 微服務測試, .NET Aspire, xUnit upgrade, TUnit, framework migration
name dotnet-testing-advanced-testcontainers-nosql description Testcontainers NoSQL 整合測試完整指南。當需要對 MongoDB 或 Redis 進行容器化整合測試時使用。涵蓋 MongoDB 文件操作、Redis 五種資料結構、Collection Fixture 模式。包含 BSON 序列化、索引效能測試、資料隔離策略與容器生命週期管理。
Make sure to use this skill whenever the user mentions Testcontainers MongoDB, Testcontainers Redis, NoSQL integration test, BSON serialization, or Redis data structure testing, even if they don't explicitly ask for NoSQL container testing.
Keywords: testcontainers mongodb, testcontainers redis, mongodb integration test, redis integration test, nosql testing, MongoDbContainer, RedisContainer, IMongoDatabase, IConnectionMultiplexer, BSON serialization, BsonDocument, 文件模型測試, 快取測試, Collection Fixture
Testcontainers NoSQL 整合測試指南
核心概念
NoSQL 測試的挑戰
NoSQL 資料庫測試與關聯式資料庫有顯著差異:
文件模型複雜度 :MongoDB 支援巢狀物件、陣列、字典等複雜結構
無固定 Schema :需要透過測試驗證資料結構的一致性
多樣化資料結構 :Redis 有五種主要資料結構,各有不同使用場景
序列化處理 :BSON (MongoDB) 與 JSON (Redis) 序列化行為需要驗證
Testcontainers 優勢
真實環境模擬 :使用實際的 MongoDB 7.0 和 Redis 7.2 容器
一致性測試 :測試結果直接反映正式環境行為
隔離性保證 :每個測試環境完全獨立
效能驗證 :可進行真實的索引效能測試
環境需求
必要套件
<Project Sdk ="Microsoft.NET.Sdk" >
<PropertyGroup >
<TargetFramework > net9.0</TargetFramework >
<Nullable > enable</ >
enable
false
Nullable
<ImplicitUsings >
</ImplicitUsings >
<IsPackable >
</IsPackable >
</PropertyGroup >
<ItemGroup >
<PackageReference Include ="MongoDB.Driver" Version ="3.7.1" />
<PackageReference Include ="MongoDB.Bson" Version ="3.7.1" />
<PackageReference Include ="StackExchange.Redis" Version ="2.12.8" />
<PackageReference Include ="Testcontainers" Version ="4.11.0" />
<PackageReference Include ="Testcontainers.MongoDb" Version ="4.11.0" />
<PackageReference Include ="Testcontainers.Redis" Version ="4.11.0" />
<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" />
<PackageReference Include ="System.Text.Json" Version ="10.0.5" />
<PackageReference Include ="Microsoft.Bcl.TimeProvider" Version ="10.0.5" />
<PackageReference Include ="Microsoft.Extensions.TimeProvider.Testing" Version ="10.4.0" />
</ItemGroup >
</Project >
套件版本說明 套件 版本 用途 MongoDB.Driver 3.7.1 MongoDB 官方驅動程式,支援最新功能 MongoDB.Bson 3.7.1 BSON 序列化處理 StackExchange.Redis 2.12.8 Redis 客戶端,支援 Redis 7.x Testcontainers.MongoDb 4.11.0 MongoDB 容器管理 Testcontainers.Redis 4.11.0 Redis 容器管理
MongoDB 容器化測試 涵蓋 MongoDB Container Fixture 建立、複雜文件模型設計(巢狀物件、陣列、字典)、BSON 序列化測試、CRUD 操作測試(含樂觀鎖定)以及索引效能與唯一性約束測試。使用 Collection Fixture 模式共享容器,節省 80% 以上的測試時間。
Redis 容器化測試 涵蓋 Redis Container Fixture 建立、快取模型設計(CacheItem 泛型包裝器、UserSession、RecentView、LeaderboardEntry)以及 Redis 五種資料結構(String、Hash、List、Set、Sorted Set)的完整測試範例,包含 TTL 過期測試與資料隔離策略。
最佳實踐
1. Collection Fixture 模式 使用 Collection Fixture 共享容器,避免每個測試重啟容器:
[CollectionDefinition("MongoDb Collection" ) ]
public class MongoDbCollectionFixture : ICollectionFixture <MongoDbContainerFixture > { }
[Collection("MongoDb Collection" ) ]
public class MyMongoTests
{
public MyMongoTests (MongoDbContainerFixture fixture )
{
}
}
2. 資料隔離策略
var user = new UserDocument
{
Username = $"testuser_{Guid.NewGuid():N} " ,
Email = $"test_{Guid.NewGuid():N} @example.com"
};
var testId = Guid.NewGuid().ToString("N" )[..8 ];
var key = $"test:{testId} :mykey" ;
3. 清理策略
await fixture.ClearDatabaseAsync();
var keys = server.Keys(database.Database);
if (keys.Any())
{
await database.KeyDeleteAsync(keys.ToArray());
}
4. 效能考量 策略 說明 Collection Fixture 容器只啟動一次,節省 80%+ 時間 資料隔離 使用唯一 Key/ID 而非清空資料庫 批次操作 使用 InsertManyAsync、SetMultipleStringAsync 索引建立 在 Fixture 初始化時建立索引
常見問題
Redis FLUSHDB 權限問題 某些 Redis 容器映像檔預設不啟用 admin 模式:
await server.FlushDatabaseAsync();
var keys = server.Keys(database.Database);
if (keys.Any())
{
await database.KeyDeleteAsync(keys.ToArray());
}
MongoDB 唯一索引重複插入
var uniqueEmail = $"test_{Guid.NewGuid():N} @example.com" ;
容器啟動超時
_container = new MongoDbBuilder()
.WithImage("mongo:7.0" )
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilCommandIsCompleted("mongosh --eval 'db.runCommand({ ping: 1 })'" ))
.Build();
相關技能
輸出格式
產生 Container Fixture 類別(MongoDB/Redis 容器管理)
產生測試類別含 Collection Fixture 設定
提供 .csproj 套件參考配置
包含資料隔離與容器生命週期管理程式碼
參考資源
原始文章 本技能內容提煉自「老派軟體工程師的測試修練 - 30 天挑戰」系列文章:
Day 22 - Testcontainers 整合測試:MongoDB 及 Redis 基礎到進階
官方文件