Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.
Testcontainers NoSQL Integration Testing Guide
Applicable Scenarios
Use this skill when asked to perform the following tasks:
- Use Testcontainers to test MongoDB document operations
- Use Testcontainers to test Redis cache services
- Create MongoDB Collection Fixture for sharing containers
- Create Redis Collection Fixture for sharing containers
- Test MongoDB BSON serialization and complex document structures
- Test MongoDB index performance and uniqueness constraints
- Test Redis five data structures (String, Hash, List, Set, Sorted Set)
- Implement data isolation strategy for NoSQL databases
Core Concepts
NoSQL Testing Challenges
NoSQL database testing has significant differences from relational database testing:
- Document Model Complexity: MongoDB supports nested objects, arrays, dictionaries, and other complex structures
- No Fixed Schema: Need to validate data structure consistency through testing
- Diverse Data Structures: Redis has five main data structures, each with different use cases
- Serialization Handling: BSON (MongoDB) and JSON (Redis) serialization behavior needs validation
Testcontainers Advantages
- Real Environment Simulation: Uses actual MongoDB 7.0 and Redis 7.2 containers
- Consistent Testing: Test results directly reflect production environment behavior
- Isolation Guarantee: Each test environment is completely independent
- Performance Validation: Can perform real index performance testing
Environment Requirements
Required Packages
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<!-- MongoDB related packages -->
<PackageReference Include="MongoDB.Driver" Version="3.0.0" />
<PackageReference Include="MongoDB.Bson" Version="3.0.0" />
<!-- Redis related packages -->
<PackageReference Include="StackExchange.Redis" Version="2.8.16" />
<!-- Testcontainers -->
<PackageReference Include="Testcontainers" Version="4.0.0" />
<PackageReference Include="Testcontainers.MongoDb" Version="4.0.0" />
<PackageReference Include="Testcontainers.Redis" Version="4.0.0" />
<!-- Test frameworks -->
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />
<PackageReference Include="AwesomeAssertions" Version="9.1.0" />
<!-- JSON serialization and time testing -->
<PackageReference Include="System.Text.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.Bcl.TimeProvider" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="9.0.0" />
</ItemGroup>
</Project>
```text
### Package Version Notes
| Package | Version | Purpose |
| ------- | ------- | ------- |
| MongoDB.Driver | 3.0.0 | MongoDB official driver, supports latest features |
| MongoDB.Bson | 3.0.0 | BSON serialization handling |
| StackExchange.Redis | 2.8.16 | Redis client, supports Redis 7.x |
| Testcontainers.MongoDb | 4.0.0 | MongoDB container management |
| Testcontainers.Redis | 4.0.0 | Redis container management |
---
## MongoDB Containerized Testing
Covers MongoDB Container Fixture creation, complex document model design (nested objects, arrays, dictionaries), BSON serialization testing, CRUD operation testing (including optimistic locking), and index performance and uniqueness constraint testing. Uses Collection Fixture pattern to share containers, saving 80%+ test time.
> 📖 Complete code examples please refer to [MongoDB Containerized Testing Detailed Guide](references/mongodb-testing.md)
---
## Redis Containerized Testing
Covers Redis Container Fixture creation, cache model design (CacheItem generic wrapper, UserSession, RecentView, LeaderboardEntry), and complete testing examples for Redis five data structures (String, Hash, List, Set, Sorted Set), including TTL expiration testing and data isolation strategy.
> 📖 Complete code examples please refer to [Redis Containerized Testing Detailed Guide](references/redis-testing.md)
---
## Best Practices
### 1. Collection Fixture Pattern
Use Collection Fixture to share containers, avoid restarting containers for each test:
```csharp
// Define collection
[CollectionDefinition("MongoDb Collection")]
public class MongoDbCollectionFixture : ICollectionFixture<MongoDbContainerFixture> { }
// Use collection
[Collection("MongoDb Collection")]
public class MyMongoTests
{
public MyMongoTests(MongoDbContainerFixture fixture)
{
// Use shared container
}
}
```text
### 2. Data Isolation Strategy
Ensure tests don't interfere with each other:
```csharp
// MongoDB: use unique Email/Username
var user = new UserDocument
{
Username = $"testuser_{Guid.NewGuid():N}",
Email = $"test_{Guid.NewGuid():N}@example.com"
};
// Redis: use unique Key prefix
var testId = Guid.NewGuid().ToString("N")[..8];
var key = $"test:{testId}:mykey";
```text
### 3. Cleanup Strategy
```csharp
// MongoDB: cleanup after tests
await fixture.ClearDatabaseAsync();
// Redis: use KeyDelete instead of FLUSHDB (avoid permission issues)
var keys = server.Keys(database.Database);
if (keys.Any())
{
await database.KeyDeleteAsync(keys.ToArray());
}
```text
### 4. Performance Considerations
| Strategy | Description |
| -------- | ----------- |
| Collection Fixture | Container only starts once, saves 80%+ time |
| Data Isolation | Use unique Key/ID instead of clearing database |
| Batch Operations | Use InsertManyAsync, SetMultipleStringAsync |
| Index Creation | Create indexes during Fixture initialization |
---
## Common Issues
### Redis FLUSHDB Permission Issue
Some Redis container images don't enable admin mode by default:
```csharp
// ❌ Error: may fail
await server.FlushDatabaseAsync();
// ✅ Correct: use KeyDelete
var keys = server.Keys(database.Database);
if (keys.Any())
{
await database.KeyDeleteAsync(keys.ToArray());
}
```text
### MongoDB Unique Index Duplicate Insert
```csharp
// Use unique Email during testing to avoid conflicts
var uniqueEmail = $"test_{Guid.NewGuid():N}@example.com";
```text
### Container Startup Timeout
```csharp
// Increase wait time
_container = new MongoDbBuilder()
.WithImage("mongo:7.0")
.WithWaitStrategy(Wait.ForUnixContainer()
.UntilPortIsAvailable(27017))
.Build();
```text
---
## Related Skills
- [testcontainers-database](../testcontainers-database/SKILL.md) - PostgreSQL/MSSQL containerized testing
- [aspnet-integration-testing](../aspnet-integration-testing/SKILL.md) - ASP.NET Core integration testing
- [nsubstitute-mocking](../../dotnet-testing/nsubstitute-mocking/SKILL.md) - Test doubles and Mock
---
## Reference Resources
### Original Articles
This skill content is distilled from the "Old School Software Engineer's Testing Practice - 30 Day Challenge" article series:
- **Day 22 - Testcontainers Integration Testing: MongoDB and Redis from Basic to Advanced**
- Article: https://ithelp.ithome.com.tw/articles/10376740
- Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day22
### Official Documentation
- [Testcontainers Official Website](https://testcontainers.com/)
- [.NET Testcontainers Documentation](https://dotnet.testcontainers.org/)
- [MongoDB.Driver Official Documentation](https://www.mongodb.com/docs/drivers/csharp/)
- [StackExchange.Redis Official Documentation](https://stackexchange.github.io/StackExchange.Redis/)
- [xUnit Collection Fixtures](https://xunit.net/docs/shared-context#collection-fixture)
1---2name: dotnet-testing-advanced-testcontainers-nosql3category: testing4subcategory: integration5description: |6 Complete guide for Testcontainers NoSQL integration testing. Use when containerized integration testing for MongoDB or Redis. Covers MongoDB document operations, Redis five data structures, Collection Fixture pattern. Includes BSON serialization, index performance testing, data isolation strategy, and container lifecycle management.7 Keywords: testcontainers mongodb, testcontainers redis, mongodb integration test, redis integration test, nosql testing, MongoDbContainer, RedisContainer, IMongoDatabase, IConnectionMultiplexer, BSON serialization, BsonDocument, document model testing, cache testing, Collection Fixture8targets: ['*']9license: MIT10metadata:11 author: Kevin Tseng12 version: '1.0.0'13 tags: 'testcontainers, mongodb, redis, nosql, integration-testing, bson'14 related_skills: 'advanced-testcontainers-database, advanced-aspire-testing, advanced-webapi-integration-testing'15claudecode: {}16opencode: {}17codexcli:18 short-description: '.NET skill guidance for dotnet-testing-advanced-testcontainers-nosql'19copilot: {}20geminicli: {}21antigravity: {}22---2324Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.2526# Testcontainers NoSQL Integration Testing Guide2728## Applicable Scenarios2930Use this skill when asked to perform the following tasks:3132- Use Testcontainers to test MongoDB document operations33- Use Testcontainers to test Redis cache services34- Create MongoDB Collection Fixture for sharing containers35- Create Redis Collection Fixture for sharing containers36- Test MongoDB BSON serialization and complex document structures37- Test MongoDB index performance and uniqueness constraints38- Test Redis five data structures (String, Hash, List, Set, Sorted Set)39- Implement data isolation strategy for NoSQL databases4041## Core Concepts4243### NoSQL Testing Challenges4445NoSQL database testing has significant differences from relational database testing:46471. **Document Model Complexity**: MongoDB supports nested objects, arrays, dictionaries, and other complex structures482. **No Fixed Schema**: Need to validate data structure consistency through testing493. **Diverse Data Structures**: Redis has five main data structures, each with different use cases504. **Serialization Handling**: BSON (MongoDB) and JSON (Redis) serialization behavior needs validation5152### Testcontainers Advantages5354- **Real Environment Simulation**: Uses actual MongoDB 7.0 and Redis 7.2 containers55- **Consistent Testing**: Test results directly reflect production environment behavior56- **Isolation Guarantee**: Each test environment is completely independent57- **Performance Validation**: Can perform real index performance testing5859## Environment Requirements6061### Required Packages6263````xml64<Project Sdk="Microsoft.NET.Sdk">65 <PropertyGroup>66 <TargetFramework>net9.0</TargetFramework>67 <Nullable>enable</Nullable>68 <ImplicitUsings>enable</ImplicitUsings>69 <IsPackable>false</IsPackable>70 </PropertyGroup>7172 <ItemGroup>73 <!-- MongoDB related packages -->74 <PackageReference Include="MongoDB.Driver" Version="3.0.0" />75 <PackageReference Include="MongoDB.Bson" Version="3.0.0" />7677 <!-- Redis related packages -->78 <PackageReference Include="StackExchange.Redis" Version="2.8.16" />7980 <!-- Testcontainers -->81 <PackageReference Include="Testcontainers" Version="4.0.0" />82 <PackageReference Include="Testcontainers.MongoDb" Version="4.0.0" />83 <PackageReference Include="Testcontainers.Redis" Version="4.0.0" />8485 <!-- Test frameworks -->86 <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />87 <PackageReference Include="xunit" Version="2.9.3" />88 <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />89 <PackageReference Include="AwesomeAssertions" Version="9.1.0" />9091 <!-- JSON serialization and time testing -->92 <PackageReference Include="System.Text.Json" Version="9.0.0" />93 <PackageReference Include="Microsoft.Bcl.TimeProvider" Version="9.0.0" />94 <PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="9.0.0" />95 </ItemGroup>96</Project>97```text9899### Package Version Notes100101| Package | Version | Purpose |102| ------- | ------- | ------- |103| MongoDB.Driver | 3.0.0 | MongoDB official driver, supports latest features |104| MongoDB.Bson | 3.0.0 | BSON serialization handling |105| StackExchange.Redis | 2.8.16 | Redis client, supports Redis 7.x |106| Testcontainers.MongoDb | 4.0.0 | MongoDB container management |107| Testcontainers.Redis | 4.0.0 | Redis container management |108109---110111## MongoDB Containerized Testing112113Covers MongoDB Container Fixture creation, complex document model design (nested objects, arrays, dictionaries), BSON serialization testing, CRUD operation testing (including optimistic locking), and index performance and uniqueness constraint testing. Uses Collection Fixture pattern to share containers, saving 80%+ test time.114115> 📖 Complete code examples please refer to [MongoDB Containerized Testing Detailed Guide](references/mongodb-testing.md)116117---118119## Redis Containerized Testing120121Covers Redis Container Fixture creation, cache model design (CacheItem generic wrapper, UserSession, RecentView, LeaderboardEntry), and complete testing examples for Redis five data structures (String, Hash, List, Set, Sorted Set), including TTL expiration testing and data isolation strategy.122123> 📖 Complete code examples please refer to [Redis Containerized Testing Detailed Guide](references/redis-testing.md)124125---126127## Best Practices128129### 1. Collection Fixture Pattern130131Use Collection Fixture to share containers, avoid restarting containers for each test:132133```csharp134// Define collection135[CollectionDefinition("MongoDb Collection")]136public class MongoDbCollectionFixture : ICollectionFixture<MongoDbContainerFixture> { }137138// Use collection139[Collection("MongoDb Collection")]140public class MyMongoTests141{142 public MyMongoTests(MongoDbContainerFixture fixture)143 {144 // Use shared container145 }146}147```text148149### 2. Data Isolation Strategy150151Ensure tests don't interfere with each other:152153```csharp154// MongoDB: use unique Email/Username155var user = new UserDocument156{157 Username = $"testuser_{Guid.NewGuid():N}",158 Email = $"test_{Guid.NewGuid():N}@example.com"159};160161// Redis: use unique Key prefix162var testId = Guid.NewGuid().ToString("N")[..8];163var key = $"test:{testId}:mykey";164```text165166### 3. Cleanup Strategy167168```csharp169// MongoDB: cleanup after tests170await fixture.ClearDatabaseAsync();171172// Redis: use KeyDelete instead of FLUSHDB (avoid permission issues)173var keys = server.Keys(database.Database);174if (keys.Any())175{176 await database.KeyDeleteAsync(keys.ToArray());177}178```text179180### 4. Performance Considerations181182| Strategy | Description |183| -------- | ----------- |184| Collection Fixture | Container only starts once, saves 80%+ time |185| Data Isolation | Use unique Key/ID instead of clearing database |186| Batch Operations | Use InsertManyAsync, SetMultipleStringAsync |187| Index Creation | Create indexes during Fixture initialization |188189---190191## Common Issues192193### Redis FLUSHDB Permission Issue194195Some Redis container images don't enable admin mode by default:196197```csharp198// ❌ Error: may fail199await server.FlushDatabaseAsync();200201// ✅ Correct: use KeyDelete202var keys = server.Keys(database.Database);203if (keys.Any())204{205 await database.KeyDeleteAsync(keys.ToArray());206}207```text208209### MongoDB Unique Index Duplicate Insert210211```csharp212// Use unique Email during testing to avoid conflicts213var uniqueEmail = $"test_{Guid.NewGuid():N}@example.com";214```text215216### Container Startup Timeout217218```csharp219// Increase wait time220_container = new MongoDbBuilder()221 .WithImage("mongo:7.0")222 .WithWaitStrategy(Wait.ForUnixContainer()223 .UntilPortIsAvailable(27017))224 .Build();225```text226227---228229## Related Skills230231- [testcontainers-database](../testcontainers-database/SKILL.md) - PostgreSQL/MSSQL containerized testing232- [aspnet-integration-testing](../aspnet-integration-testing/SKILL.md) - ASP.NET Core integration testing233- [nsubstitute-mocking](../../dotnet-testing/nsubstitute-mocking/SKILL.md) - Test doubles and Mock234235---236237## Reference Resources238239### Original Articles240241This skill content is distilled from the "Old School Software Engineer's Testing Practice - 30 Day Challenge" article series:242243- **Day 22 - Testcontainers Integration Testing: MongoDB and Redis from Basic to Advanced**244 - Article: https://ithelp.ithome.com.tw/articles/10376740245 - Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day22246247### Official Documentation248249- [Testcontainers Official Website](https://testcontainers.com/)250- [.NET Testcontainers Documentation](https://dotnet.testcontainers.org/)251- [MongoDB.Driver Official Documentation](https://www.mongodb.com/docs/drivers/csharp/)252- [StackExchange.Redis Official Documentation](https://stackexchange.github.io/StackExchange.Redis/)253- [xUnit Collection Fixtures](https://xunit.net/docs/shared-context#collection-fixture)254````