We have seen EF core supports multiple data providers. EF core can use variety of databases as its data store. In this article, we are going to demonstrate how in-memory database
provider
can be used for unit testing an EF core based project.
Why ?
EF core provides various database providers to interact with databases. Functionality provided by a data provider depends on features supported by underlying database. Hence it is always better to test the EF core based application with actual database.
But it means, every time you want to test the application, it would need to have a hosted application with a database server. If you write automated tests which interact with actual database, those tests would generate a lot of data daily. Thus, having a database server certainly has a cost associated with it and it might not make sense to have actual database server every time.
Hence, for some of the automated tests at least, you may want to have a stub which would test almost everything in the EF core based data access layer.
There are various options for this purpose. We can use Sqlite database in automated tests irrespective of which database is used by application in production. Sqlite database provider also has option to have in-memory database, so it would not even need a path to create a file.
But in this article, we will not talk about Sqlite usage in tests. In this article, let’s talk only about in-memory database provider.
Prerequisites
We are going to use the blog demo application. You can download the application from my GitHub repository. Also, we will use xUnit test project
for this demonstration.
The plan is to write a simple unit test for PostsRepository.
Project and References
Create a new xUnit test project
and add references to Blog.Data project. Then add reference to – Microsoft.EntityFrameworkCore.InMemory – NuGet package to this new project.
Once these references have been added, add a new class PostsRepositoryTests.
Posts Repository Tests
In the new class, we need to setup a blog context which can be injected to a repository. When we added an API layer for blog demo app, we called AddDbContext method, which automatically constructed DbContextOptions which is required to construct BlogContext.
In the test file, we will have to create DbContextOptions using DbContextOptionsBuilder class as shown in below code snippet. Once DbContextOptions are created, they can be used to construct a BlogContext instance.
Below code snippet tests a method from repository, which is responsible for saving new post in database.
Wrapping up
We have seen how easy it is to use in-memory database provider. It is very easy to write unit tests and the tests written using in-memory provider is also similar to any other unit tests. The only difference is how DbContextOptions are built.
I hope you find this information helpful. Let me know your thoughts.