DbContextOptionsBuilder configures the options and services used by an EF Core DbContext. For tests, it can connect the context to a SQLite database held in memory. section 36.4
A typical SQLite in-memory test setup follows these steps:
- Create a SqliteConnection with "DataSource=:memory:" and open it manually. section 36.4
- Construct DbContextOptionsBuilder<AppDbContext>, call UseSqlite(connection), and retrieve the configured options through Options. section 36.4
- Pass the options to AppDbContext, call EnsureCreated(), add test data, and use separate context instances for later queries. section 36.4
Configure a SQLite in-memory context
var connection = new SqliteConnection("DataSource=:memory:"); connection.Open(); var options = new DbContextOptionsBuilder<AppDbContext>() .UseSqlite(connection) .Options; using var context = new AppDbContext(options); context.Database.EnsureCreated(); section 36.4
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
}
}
The complete test listing extends this setup with recipe data and assertions against the configured context. section 36.4
