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-nosql-33description: 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 Fixture4---5Source: kevintsengtw/dotnet-testing-agent-skills (MIT). Ported into dotnet-agent-harness.67# Testcontainers NoSQL Integration Testing Guide89## Applicable Scenarios1011Use this skill when asked to perform the following tasks:1213- Use Testcontainers to test MongoDB document operations14- Use Testcontainers to test Redis cache services15- Create MongoDB Collection Fixture for sharing containers16- Create Redis Collection Fixture for sharing containers17- Test MongoDB BSON serialization and complex document structures18- Test MongoDB index performance and uniqueness constraints19- Test Redis five data structures (String, Hash, List, Set, Sorted Set)20- Implement data isolation strategy for NoSQL databases2122## Core Concepts2324### NoSQL Testing Challenges2526NoSQL database testing has significant differences from relational database testing:27281. **Document Model Complexity**: MongoDB supports nested objects, arrays, dictionaries, and other complex structures292. **No Fixed Schema**: Need to validate data structure consistency through testing303. **Diverse Data Structures**: Redis has five main data structures, each with different use cases314. **Serialization Handling**: BSON (MongoDB) and JSON (Redis) serialization behavior needs validation3233### Testcontainers Advantages3435- **Real Environment Simulation**: Uses actual MongoDB 7.0 and Redis 7.2 containers36- **Consistent Testing**: Test results directly reflect production environment behavior37- **Isolation Guarantee**: Each test environment is completely independent38- **Performance Validation**: Can perform real index performance testing3940## Environment Requirements4142### Required Packages4344````xml45<Project Sdk="Microsoft.NET.Sdk">46 <PropertyGroup>47 <TargetFramework>net9.0</TargetFramework>48 <Nullable>enable</Nullable>49 <ImplicitUsings>enable</ImplicitUsings>50 <IsPackable>false</IsPackable>51 </PropertyGroup>5253 <ItemGroup>54 <!-- MongoDB related packages -->55 <PackageReference Include="MongoDB.Driver" Version="3.0.0" />56 <PackageReference Include="MongoDB.Bson" Version="3.0.0" />5758 <!-- Redis related packages -->59 <PackageReference Include="StackExchange.Redis" Version="2.8.16" />6061 <!-- Testcontainers -->62 <PackageReference Include="Testcontainers" Version="4.0.0" />63 <PackageReference Include="Testcontainers.MongoDb" Version="4.0.0" />64 <PackageReference Include="Testcontainers.Redis" Version="4.0.0" />6566 <!-- Test frameworks -->67 <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />68 <PackageReference Include="xunit" Version="2.9.3" />69 <PackageReference Include="xunit.runner.visualstudio" Version="2.8.2" />70 <PackageReference Include="AwesomeAssertions" Version="9.1.0" />7172 <!-- JSON serialization and time testing -->73 <PackageReference Include="System.Text.Json" Version="9.0.0" />74 <PackageReference Include="Microsoft.Bcl.TimeProvider" Version="9.0.0" />75 <PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="9.0.0" />76 </ItemGroup>77</Project>78```text7980### Package Version Notes8182| Package | Version | Purpose |83| ------- | ------- | ------- |84| MongoDB.Driver | 3.0.0 | MongoDB official driver, supports latest features |85| MongoDB.Bson | 3.0.0 | BSON serialization handling |86| StackExchange.Redis | 2.8.16 | Redis client, supports Redis 7.x |87| Testcontainers.MongoDb | 4.0.0 | MongoDB container management |88| Testcontainers.Redis | 4.0.0 | Redis container management |8990---9192## MongoDB Containerized Testing9394Covers 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.9596> 📖 Complete code examples please refer to [MongoDB Containerized Testing Detailed Guide](references/mongodb-testing.md)9798---99100## Redis Containerized Testing101102Covers 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.103104> 📖 Complete code examples please refer to [Redis Containerized Testing Detailed Guide](references/redis-testing.md)105106---107108## Best Practices109110### 1. Collection Fixture Pattern111112Use Collection Fixture to share containers, avoid restarting containers for each test:113114```csharp115// Define collection116[CollectionDefinition("MongoDb Collection")]117public class MongoDbCollectionFixture : ICollectionFixture<MongoDbContainerFixture> { }118119// Use collection120[Collection("MongoDb Collection")]121public class MyMongoTests122{123 public MyMongoTests(MongoDbContainerFixture fixture)124 {125 // Use shared container126 }127}128```text129130### 2. Data Isolation Strategy131132Ensure tests don't interfere with each other:133134```csharp135// MongoDB: use unique Email/Username136var user = new UserDocument137{138 Username = $"testuser_{Guid.NewGuid():N}",139 Email = $"test_{Guid.NewGuid():N}@example.com"140};141142// Redis: use unique Key prefix143var testId = Guid.NewGuid().ToString("N")[..8];144var key = $"test:{testId}:mykey";145```text146147### 3. Cleanup Strategy148149```csharp150// MongoDB: cleanup after tests151await fixture.ClearDatabaseAsync();152153// Redis: use KeyDelete instead of FLUSHDB (avoid permission issues)154var keys = server.Keys(database.Database);155if (keys.Any())156{157 await database.KeyDeleteAsync(keys.ToArray());158}159```text160161### 4. Performance Considerations162163| Strategy | Description |164| -------- | ----------- |165| Collection Fixture | Container only starts once, saves 80%+ time |166| Data Isolation | Use unique Key/ID instead of clearing database |167| Batch Operations | Use InsertManyAsync, SetMultipleStringAsync |168| Index Creation | Create indexes during Fixture initialization |169170---171172## Common Issues173174### Redis FLUSHDB Permission Issue175176Some Redis container images don't enable admin mode by default:177178```csharp179// ❌ Error: may fail180await server.FlushDatabaseAsync();181182// ✅ Correct: use KeyDelete183var keys = server.Keys(database.Database);184if (keys.Any())185{186 await database.KeyDeleteAsync(keys.ToArray());187}188```text189190### MongoDB Unique Index Duplicate Insert191192```csharp193// Use unique Email during testing to avoid conflicts194var uniqueEmail = $"test_{Guid.NewGuid():N}@example.com";195```text196197### Container Startup Timeout198199```csharp200// Increase wait time201_container = new MongoDbBuilder()202 .WithImage("mongo:7.0")203 .WithWaitStrategy(Wait.ForUnixContainer()204 .UntilPortIsAvailable(27017))205 .Build();206```text207208---209210## Related Skills211212- [testcontainers-database](../testcontainers-database/SKILL.md) - PostgreSQL/MSSQL containerized testing213- [aspnet-integration-testing](../aspnet-integration-testing/SKILL.md) - ASP.NET Core integration testing214- [nsubstitute-mocking](../../dotnet-testing/nsubstitute-mocking/SKILL.md) - Test doubles and Mock215216---217218## Reference Resources219220### Original Articles221222This skill content is distilled from the "Old School Software Engineer's Testing Practice - 30 Day Challenge" article series:223224- **Day 22 - Testcontainers Integration Testing: MongoDB and Redis from Basic to Advanced**225 - Article: https://ithelp.ithome.com.tw/articles/10376740226 - Sample code: https://github.com/kevintsengtw/30Days_in_Testing_Samples/tree/main/day22227228### Official Documentation229230- [Testcontainers Official Website](https://testcontainers.com/)231- [.NET Testcontainers Documentation](https://dotnet.testcontainers.org/)232- [MongoDB.Driver Official Documentation](https://www.mongodb.com/docs/drivers/csharp/)233- [StackExchange.Redis Official Documentation](https://stackexchange.github.io/StackExchange.Redis/)234- [xUnit Collection Fixtures](https://xunit.net/docs/shared-context#collection-fixture)235````