An in-memory database provider stores test data in process memory instead of persistent database storage. It lets EF Core services use a DbContext without configuring or contacting a real database, keeping tests fast, repeatable, and isolated. section 36.4 section 36.0
Choose the provider according to the behavior your test needs:
- The EF Core in-memory provider stores objects in memory and executes LINQ queries directly against them; it does not simulate a relational database. section 36.4
- The SQLite provider can run in in-memory mode and is useful when tests need a database-backed DbContext without persistent storage. section 36.4
- A real production-style database may still be preferable for integration tests because it increases the chance of detecting database-specific problems. section 36.4
Testing a RecipeService with SQLite in memory
Open a SqliteConnection using "DataSource=:memory:", configure DbContextOptionsBuilder<AppDbContext> with UseSqlite(connection), create the context, and call EnsureCreated(). Add Recipe entities, invoke RecipeService.GetRecipe(), and assert the returned view model. Keep the connection open while the test uses its contexts: SQLite preserves the in-memory database only for the lifetime of that open connection. section 36.4 section 36.5
Listing 36.13 Using the in-memory database provider to test an EF Core DbContext
[Fact]
public void GetRecipeDetails_CanLoadFromContext()
{
var connection = new SqliteConnection("DataSource=:memory:"); #1
connection.Open(); #2
var options = new DbContextOptionsBuilder<AppDbContext>() #3
.UseSqlite(connection) #3
.Options; #3
using (var context = new AppDbContext(options)) #4
{
context.Database.EnsureCreated(); #5
context.Recipes.AddRange( #6
new Recipe { RecipeId = 1, Name = "Recipe1" }, #6
new Recipe { RecipeId = 2, Name = "Recipe2" }, #6
new Recipe { RecipeId = 3, Name = "Recipe3" }); #6
context.SaveChanges(); #7
}
using (var context = new AppDbContext(options)) #8
{
var service = new RecipeService(context); #9
var recipe = service.GetRecipe (id: 2); #10
Assert.NotNull(recipe); #11
Assert.Equal(2, recipe.Id); #11
Assert.Equal("Recipe2", recipe.Name); #11
}
}
Shows the complete test setup: opening the SQLite connection, configuring EF Core, creating the schema, seeding recipes, and exercising the DbContext. section 36.4




