-
Notifications
You must be signed in to change notification settings - Fork 0
Seeding Data
Aryeh Citron edited this page May 12, 2026
·
2 revisions
The most straightforward approach — insert documents directly:
var result = InMemoryMongo.Create<Product>("products");
await result.Collection.InsertManyAsync(new[]
{
new Product { Name = "Widget", Price = 9.99m },
new Product { Name = "Gadget", Price = 19.99m },
new Product { Name = "Doohickey", Price = 29.99m }
});Use the OnDatabaseCreated or OnClientCreated callbacks to seed test data when the in-memory services are created:
services.UseInMemoryMongoDB(options =>
{
options.DatabaseName = "testdb";
options.AddCollection<Product>("products");
options.OnDatabaseCreated = db =>
{
var collection = db.GetCollection<Product>("products");
collection.InsertMany(TestData.SampleProducts());
};
});var db = result.Database as InMemoryMongoDatabase;
// Export current state
string json = db!.ExportState();
// Import state (replaces all documents)
db.ImportState(json);var db = result.Database as InMemoryMongoDatabase;
// Save to file
db!.ExportStateToFile("test-data.json");
// Load from file
db.ImportStateFromFile("test-data.json");var db = result.Database as InMemoryMongoDatabase;
db?.ClearDocuments();The simplest isolation approach — create a new in-memory instance per test:
public class ProductTests
{
[Fact]
public async Task Test1()
{
var result = InMemoryMongo.Create<Product>("products");
// Fresh, empty collection
}
[Fact]
public async Task Test2()
{
var result = InMemoryMongo.Create<Product>("products");
// Another fresh, empty collection — no cross-test contamination
}
}- State Persistence — Automatic persistence between test runs
- Setup Guide — DI callback patterns
Getting Started
Integration & Dependency Injection
Data Management
Reference
- Feature Comparison
- Features
- Filter & Update Operators
- Aggregation Pipeline
- LINQ Support
- API Reference
Help