Unit testing repository using In Memory database in entity framework core
In entity framework 6 there was no built-in way of doing repository testing using an in-memory database. There were third party libraries like effort but they were also not fully compatible or keeping up with all the updated versions of entity framework .
Thankfully in entity framework core, this problem is resolved and support for the in-memory database is provided.
For using InMemory database you would need to install Microsoft.EntityFrameworkCore.InMemory nuget package and ensure that your DbContext class has a constructor which takes object of DBContextOptions
public class MyApplicationContext : DBContext { public MyApplicationContext() { } public MyApplicationContext(DbContextOptions<MyApplicationContext> options) : base(options) { } }
Below is a simple unit test using the in-memory database
public static MyApplicationContext GetTestDbContext(string dbName) { // Create db context options specifying in memory database var options = new DbContextOptionsBuilder<MyApplicationContext>() .UseInMemoryDatabase(databaseName: dbName) .Options; //Use this to instantiate the db context return new MyApplicationContext(options); } private MyApplicationContext GetTestDatabase() { //Get the context var testContext = GetTestDbContext(nameof(AddCategory_ShouldAddNewCategory_ToDatabase)); //Add some dummy categories to in memory db var fixture = new Fixture(); var mockCategories = fixture.Create<List<Category>>(); testContext.AddRange(mockCategories); return testContext; } [Fact] public void AddCategory_ShouldAddNewCategory_ToDatabase() { //arrange MyApplicationContext testContext = GetTestDatabase(); //category to be inserted var testCategory = new Category { Id = 1, Name = "Test category", User = new MyApplicationUser { Id = "User_1111" } }; var mockLogger = new MockLogger(); //act var repostiory = new MyApplicationRepository(testContext, mockLogger); repostiory.AddCategory(testCategory); //assert testContext.Categories.ShouldContain(testCategory); }
To know more about strategies for testing using ef core including in memory database you can refer this excellent Pluralsight course which talks about different aspects on this topic.