Skip to content

Seeding Data

Aryeh Citron edited this page May 12, 2026 · 2 revisions

Seeding Data

Seeding via SDK Methods

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 }
});

Seeding via Dependency Injection Callbacks

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());
    };
});

Seeding from a File or Snapshot

Export / Import JSON

var db = result.Database as InMemoryMongoDatabase;

// Export current state
string json = db!.ExportState();

// Import state (replaces all documents)
db.ImportState(json);

File-based

var db = result.Database as InMemoryMongoDatabase;

// Save to file
db!.ExportStateToFile("test-data.json");

// Load from file
db.ImportStateFromFile("test-data.json");

Resetting Data Between Tests

Clear all documents

var db = result.Database as InMemoryMongoDatabase;
db?.ClearDocuments();

Fresh collection per test

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
    }
}

See Also

Clone this wiki locally