Posted by Anuraj on Tuesday, August 6, 2019 Reading time :2 minutes
This post is about how to mock entity framework DbContext class for unit testing without any third party framework. The dotnet core framework designed and developed considering testability of the apps in mind. Usually for testing the applications which interacts with database, we used to follow two approaches 1) We will be using a repository layer to interact with Database and using any mock framework (without a mocking framework also we can implement it.), we will mock the repository and test the application. 2) Use In Memory Database provider instead of the actual database provider. In this post, I am showing the second approach, the actual code is using SQL Server provider. And for unit testing I am using In Memory provider for EF Core.
Here is my controller code - which I am going to test.
Here is the DbContext class.
And finally my startup.cs -
So when I am writing the test, I need to create the instance of the controller and which will take the
DatabaseContext class as the input parameter. So to create the
DatabaseContext class with In Memory provider, we can use the following code.
In the above code snippet, I am creating an instance of
DbContextOptionsBuilder with In Memory provider and use it as the constructor parameter for the
DatabaseContext class. And for testing purposes I am seeding the database as well. And we can use the DbContext class in the test code like this.
In this post I explained how to use the InMemory provider from EF Core to enable Unit testing classes with DbContext. If you’re not using any pattern like repository in your code, it is easy to use this implementation to test controllers or classes - instead of writing code for making the application testable.
Happy Programming :)
What do you think? I would like to hear your thoughts, suggestions, and questions in the comments section below.