Tutorials Entity Framework Core Tutorial
InMemory Database for EF Core Tests
InMemory Database for EF Core Tests: free step-by-step lesson with examples, common mistakes, and interview tips — part of Entity Framework Core Tutorial on Toolliyo Academy.
On this page
Entity Framework Core Tutorial · Lesson 83 of 100
InMemory Database for EF Core Tests
Beginner ✓ → Intermediate ✓ → Advanced ✓ → Professional
Professional · 4 — Real projects · ~10 min · Module 9: Testing & Debugging
What is this?
EF Core InMemory provider stores data in process memory — quick for tests but diverges from SQL Server on constraints, transactions, and raw SQL.
Why should you care?
ShopNest handler smoke tests use InMemory for speed when testing non-SQL-specific logic — not for constraint validation.
See it live — copy this example
Paste into a .NET project with EF Core packages, then run with LocalDB/SQL Server (dotnet ef / dotnet run).
var options = new DbContextOptionsBuilder<ShopNestDbContext>()
.UseInMemoryDatabase($"ShopNestTest_{Guid.NewGuid()}")
.Options;
await using var db = new ShopNestDbContext(options);
db.Products.Add(new Product { Name = "Test", Price = 1, Sku = "T1" });
await db.SaveChangesAsync();
Assert.Equal(1, await db.Products.CountAsync());
What happened?
- Unique database name per test avoids cross-test pollution.
- InMemory accepts SaveChanges without real SQL Server — good for handler wiring tests only.
Practice next
- Use unique InMemory database name per test class or test.
- Do not rely on InMemory for FK, unique index, or transaction tests.
- Prefer SQLite or LocalDB for constraint fidelity.
- Run same test on InMemory and SQLite — compare failure differences on FK test.
- Seed InMemory with HasData equivalent manual Add in test setup.
Remember
InMemory is fast isolated fake DB. Behavior differs from SQL Server. Use for simple CRUD handler smoke tests.
ShopNest handler smoke
MediatR handler tests use InMemory to verify handler calls SaveChanges once.
Outcome: Fast feedback; SQL fidelity tests run separately in integration job.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!