Author : HASSAN MD TAREQ

SQLite

  • Install-Package Microsoft.AspNetCore.All
  • NuGet package Microsoft.EntityFrameworkCore.Sqlite (already included in Microsoft.AspNetCore.All metapackage)
public static DbContextOptions<T> CreateOptions<T>(bool throwOnClientServerWarning = true) where T : DbContext
{
	var connectionStringBuilder = new SqliteConnectionStringBuilder { DataSource = ":memory:" };
	var connectionString = connectionStringBuilder.ToString();
	var connection = new SqliteConnection(connectionString);
	connection.Open();

	// create in-memory context
	var builder = new DbContextOptionsBuilder<T>();
	builder.UseSqlite(connection);
	builder.ApplyOtherOptionSettings(throwOnClientServerWarning);
	return builder.Options;
}

[Fact]
public void TestSQLiteOk()
{
	//SETUP
	var options = SQLiteInMemory.CreateOptions<EfCoreContext>();
	using(var context = new EfCoreContext(options))
	{
		context.Database.EnsureCreated();

		//ATTEMPT
		context.SeedDatabaseFourBooks();

		//VERIFY
		context.Books.Count().ShouldEqual(4);
	}
}

SQL Server

  • Using sqlserver for unit test: https://www.codejourney.net/2017/07/entity-framework-core-database-initialization-with-unit-test/
  • Better unit test data: https://www.thereformedprogrammer.net/getting-better-data-for-unit-testing-your-ef-core-applications/