Skip to content

Version320 Sqlite in memory test database

Jon P Smith edited this page Jan 4, 2021 · 2 revisions

Version 3.2.0: Helpers to create an in-memory Sqlite database

The sqliteInMemory.CreateOptions<T> method will create options that will provide a sqlite, in-memory database for unit testing. The code below shows how is can be used.

[Fact]
public void TestSqliteOk()
{
    //SETUP
    var options = SqliteInMemory.CreateOptions<EfCoreContext>(); 
    using (var context = new EfCoreContext(options))
    {
        //... rest of unit test goes here

NOTE: If you are using SQLite with .Net 4.7.1 you need to call SQLitePCL.Batteries.Init() - see issue 6 raised by @CrahunGit, or the SQLitePCL docs.

EF Core 3+ ONLY (not in EF Core 2.1)

There is a optional parameter that allows you to set extra options and/or override given options in the DbContextOptionsBuilder<T> level. Below is part of the unit tests showing how to add/override options.

//... previous code removed to focus on this feature
var options2 = SqliteInMemory.CreateOptions<BookContext>(builder =>
{
    builder.UseSqlite(connection); //overrides current connection with existing connection
    builder.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); //change track option
});
using (var context = new BookContext(options2))
{
    //VERIFY
    var book = context.Books.First();
    context.Entry(book).State.ShouldEqual(EntityState.Detached);
}

EF Core 2.1 ONLY (not in EF Core 3+)

The methods has one, optional bool parameter of throwOnClientServerWarning which defaults to true, which means EF Core will throw an exception if a QueryClientEvaluationWarning is logged (NOT in EF Core 3+). Setting it to false turns off the exception.

Clone this wiki locally