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-nosql3description: 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. 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 Fixture4license: MIT5---67Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.89# Testcontainers NoSQL Integration Testing Guide1011## Applicable Scenarios1213Use this skill when asked to perform the following tasks:1415- Use Testcontainers to test MongoDB document operations16- Use Testcontainers to test Redis cache services17- Create MongoDB Collection Fixture for sharing containers18- Create Redis Collection Fixture for sharing containers19- Test MongoDB BSON serialization and complex document structures20- Test MongoDB index performance and uniqueness constraints21- Test Redis five data structures (String, Hash, List, Set, Sorted Set)22- Implement data isolation strategy for NoSQL databases2324## Core Concepts2526### NoSQL Testing Challenges2728NoSQL database testing has significant differences from relational database testing:29301. **Document Model Complexity**: MongoDB supports nested objects, arrays, dictionaries, and other complex structures312. **No Fixed Schema**: Need to validate data structure consistency through testing323. **Diverse Data Structures**: Redis has five main data structures, each with different use cases334. **Serialization Handling**: BSON (MongoDB) and JSON (Redis) serialization behavior needs validation3435### Testcontainers Advantages3637- **Real Environment Simulation**: Uses actual MongoDB 7.0 and Redis 7.2 containers38- **Consistent Testing**: Test results directly reflect production environment behavior39- **Isolation Guarantee**: Each test environment is completely independent40- **Performance Validation**: Can perform real index performance testing4142## Environment Requirements4344### Required Packages4546````xml47<Project Sdk="Microsoft.NET.Sdk">48 <PropertyGroup>49 <TargetFramework>net9.0</TargetFramework>50 <Nullable>enable</Nullable>51 <ImplicitUsings>enable</ImplicitUsings>52 <IsPackable>false</IsPackable>53 </PropertyGroup>5455 <ItemGroup>56 <!-- MongoDB related packages -->57 <PackageReference Include="MongoDB.Driver" Version="3.0.0" />58 <PackageReference Include="MongoDB.Bson" Version="3.0.0" />5960 <!-- Redis related packages -->61 <PackageReference Include="StackExchange.Redis" Version="2.8.16" />6263 <!-- Testcontainers -->64 <PackageReference Include="Testcontainers" Version="4.0.0" />65 <PackageReference Include="Testcontainers.MongoDb" Version="4.0.0" />66 <PackageReference Include="Testcontainers.Redis" Version="4.0.0" />6768 <!-- Test frameworks -->69 <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />70 <PackageReference Include="xunit" Version="2.9.3" />71 <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />72 <PackageReference Include="AwesomeAssertions" Version="9.1.0" />7374 <!-- JSON serialization and time testing -->75 <PackageReference Include="System.Text.Json" Version="9.0.0" />76 <PackageReference Include="Microsoft.Bcl.TimeProvider" Version="9.0.0" />77 <PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="9.0.0" />78 </ItemGroup>79</Project>80```text8182### Package Version Notes8384| Package | Version | Purpose |85| ------- | ------- | ------- |86| MongoDB.Driver | 3.0.0 | MongoDB official driver, supports latest features |87| MongoDB.Bson | 3.0.0 | BSON serialization handling |88| StackExchange.Redis | 2.8.16 | Redis client, supports Redis 7.x |89| Testcontainers.MongoDb | 4.0.0 | MongoDB container management |90| Testcontainers.Redis | 4.0.0 | Redis container management |9192---9394## MongoDB Containerized Testing9596Covers 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.9798> 📖 Complete code examples please refer to [MongoDB Containerized Testing Detailed Guide](references/mongodb-testing.md)99100---101102## Redis Containerized Testing103104Covers 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.105106> 📖 Complete code examples please refer to [Redis Containerized Testing Detailed Guide](references/redis-testing.md)107108---109110## Best Practices111112### 1. Collection Fixture Pattern113114Use Collection Fixture to share containers, avoid restarting containers for each test:115116```csharp117// Define collection118[CollectionDefinition("MongoDb Collection")]119public class MongoDbCollectionFixture : ICollectionFixture<MongoDbContainerFixture> { }120121// Use collection122[Collection("MongoDb Collection")]123public class MyMongoTests124{125 public MyMongoTests(MongoDbContainerFixture fixture)126 {127 // Use shared container128 }129}130```text131132### 2. Data Isolation Strategy133134Ensure tests don't interfere with each other:135136```csharp137// MongoDB: use unique Email/Username138var user = new UserDocument139{140 Username = $"testuser_{Guid.NewGuid():N}",141 Email = $"test_{Guid.NewGuid():N}@example.com"142};143144// Redis: use unique Key prefix145var testId = Guid.NewGuid().ToString("N")[..8];146var key = $"test:{testId}:mykey";147```text148149### 3. Cleanup Strategy150151```csharp152// MongoDB: cleanup after tests153await fixture.ClearDatabaseAsync();154155// Redis: use KeyDelete instead of FLUSHDB (avoid permission issues)156var keys = server.Keys(database.Database);157if (keys.Any())158{159 await database.KeyDeleteAsync(keys.ToArray());160}161```text162163### 4. Performance Considerations164165| Strategy | Description |166| -------- | ----------- |167| Collection Fixture | Container only starts once, saves 80%+ time |168| Data Isolation | Use unique Key/ID instead of clearing database |169| Batch Operations | Use InsertManyAsync, SetMultipleStringAsync |170| Index Creation | Create indexes during Fixture initialization |171172---173174## Common Issues175176### Redis FLUSHDB Permission Issue177178Some Redis container images don't enable admin mode by default:179180```csharp181// ❌ Error: may fail182await server.FlushDatabaseAsync();183184// ✅ Correct: use KeyDelete185var keys = server.Keys(database.Database);186if (keys.Any())187{188 await database.KeyDeleteAsync(keys.ToArray());189}190```text191192### MongoDB Unique Index Duplicate Insert193194```csharp195// Use unique Email during testing to avoid conflicts196var uniqueEmail = $"test_{Guid.NewGuid():N}@example.com";197```text198199### Container Startup Timeout200201```csharp202// Increase wait time203_container = new MongoDbBuilder()204 .WithImage("mongo:7.0")205 .WithWaitStrategy(Wait.ForUnixContainer()206 .UntilPortIsAvailable(27017))207 .Build();208```text209210---211212## Related Skills213214- [testcontainers-database](../testcontainers-database/SKILL.md) - PostgreSQL/MSSQL containerized testing215- [aspnet-integration-testing](../aspnet-integration-testing/SKILL.md) - ASP.NET Core integration testing216- [nsubstitute-mocking](../../dotnet-testing/nsubstitute-mocking/SKILL.md) - Test doubles and Mock217218---219220## Reference Resources221222### Original Articles223224This skill content is distilled from the "Old School Software Engineer's Testing Practice - 30 Day Challenge" article series:225226- **Day 22 - Testcontainers Integration Testing: MongoDB and Redis from Basic to Advanced**227 - Article: https://ithelp.ithome.com.tw/articles/10376740228 - Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day22229230### Official Documentation231232- [Testcontainers Official Website](https://testcontainers.com/)233- [.NET Testcontainers Documentation](https://dotnet.testcontainers.org/)234- [MongoDB.Driver Official Documentation](https://www.mongodb.com/docs/drivers/csharp/)235- [StackExchange.Redis Official Documentation](https://stackexchange.github.io/StackExchange.Redis/)236- [xUnit Collection Fixtures](https://xunit.net/docs/shared-context#collection-fixture)237````