Entity Framework Core: Unit Testing

Using a mocking framework

Metse
2 min readAug 19, 2017

Finding concrete documentation to implement unit testing with Entity Framework was a little challenging, in my opinion. From adding references to understanding how all the pieces fit together. There’s also a lot of controversy on whether our DAL should be tested. Entity Framework is, of course, well tested. But what isn’t tested is the database we own underneath.

We will be mocking our implementation and ensuring that it’s bug free. Mocking is simply making fun of someone by mimicking them. So, technically speaking, we’re ridiculing our implementation. In this tutorial, we’ll use Moq to work with EF Core. We’ll do the classic example of creating and fetching books.

(We’ll be using .NET Core 1.1)

Packages To Install

Install-Package Microsoft.EntityFrameworkCore -Version 1.1.2Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 1.1.2Install-Package Microsoft.EntityFrameworkCore.Design -Version 1.1.2Install-Package Microsoft.EntityFrameworkCore.Tools -Version 1.1.1

Set up Book Entity and BookContext

After this we should add this snippet under ConfigureServices method in Startup.cs for our connection string.

services.AddDbContext<BookContext>(b => 
b.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

EF Migrations & Database Update

Add-Migration InitialUpdate-Database

Book Repository

So far, all we’ve done is set up our model and create a small repository that will allow us to fetch and create books. Now we will test our implementation.

Create Unit Test Project

Now it’s time to create the tests project. Right click on your solution and select

Add > New Project > .NET Core > Unit Test Project (.NET Core)

Install-Package Moq 

Ensure you install this package in the correct default project & add a reference to the main project.

Conclusion

In conclusion, writing unit tests with Moq was quite a painless process. FYI, when I ran the tests I actually discovered bugs. (I forgot to add a parameterless constructor to my BookContext).

If you found this tutorial helpful, a clap would be appreciated :)

--

--