How To: Use EntityFramework Core In-Memory Database For Unit Testing
In this post you will learn how to use entityframework in memory database.
You can download this article project on GitHub .
In this post, I’ll show how to use the in-memory feature of Entity Framework core to create unit tests involving the database. Let’s jump right in!
Create unit tests using a real DbContext is a pain because we have to mock the entire context to achieve this. Entity Framework core makes unit tests easier to write by providing us with an in-memory database provider. It creates an in-memory representation of our DbContext , for this reason, we don’t have to worry about mocking the database.
Setup your context
First, the database configuration must be done in the
Startup.cs
class, as it usually is in ASP.NET core projects. To illustrate:
public class Startup
//...........
//Other Stuff
//...........
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
services.AddDbContext<ToDoDbContext>(
options =>
options
.UseSqlServer(Configuration.GetConnectionString("SimpleToDo")));
//...........
//Other Configurations
//...........
//...........
//Other Stuff
//...........
Next, the context should accept multiple database providers. We need a constructor which receives a
DbContextOptions
object:
public ToDoDbContext(DbContextOptions options) : base(options) { }
Finally, we can create the context with different configurations.
Create First Unit Test
We will add a new NuGet package to our unit test project. Open the package manager console and use the following command:
PM> Install-Package Microsoft.EntityFrameworkCore.InMemory
Now we can start to use the in-memory database feature.
Create a new unit test class for which functionality you want to test. In my case, it will be for the
ToDoListRepository.cs
.
public class ToDoListRepositoryTests
[Fact]
public void CreateToDoList_WithValidObject_NewListIdIsNotEqualsToZero()
//Arrange
var newToDoList = new List
Name = "Unit Test"
var sut = CreateSUT();
//Act
sut.CreateToDoList(newToDoList);
//Assert
Assert.True(newToDoList.ListId != 0);
private ToDoListRepository CreateSUT()
var dbOptions = new DbContextOptionsBuilder<ToDoDbContext>()
.UseInMemoryDatabase(databaseName: "ToDoDb")
.Options;