Mock and Unit Test with Repository Entity Framework Core

Unit Test Entity Framework Core Repository

Today in this article, we will see how to get started with Mock and Unit Test Entity Framework Core with Repository.

It is recommended to use EFCore DBContext Using a Repository Pattern as it encourages a more loosely coupled approach to access data from the database.

With Repository using EFCore the Data access code becomes testable, cleaner, maintainable, and highly extensible.

Please note that the DBContext class generated using scaffolding commands is still a concrete type.

Today in this article, we will cover below aspects,

As good practices we generally don’t write unit testing on any Scaffolded or autogenerated code rather we try mocking the module or auto-generated code (Ex.DBContext)

So with that understanding, we shall be using the InMemoryDatabase technique to create test data and the same will be set as our DBContext to perform the Unit testing.

Getting Started

Please create an XUnit Test Project and add a reference to the Service project.

To Use InMemoryDatabase please add a reference to the below Nuget package,

PM> Install-Package Microsoft.EntityFrameworkCore.InMemory -Version 3.1.2

Note: Please use the latest available version

Define InMemory Test Database for EFCore

Please create the DbContextOptionsBuilder option object to set up InMemoryDatabase.

Please use the below code base to initialize the InMemory Test Database,

  //Create In Memory Database
             var options = new DbContextOptionsBuilder<EmployeeContext>()
            .UseInMemoryDatabase(databaseName: "EmployeeDataBase")
            .Options;

Create Mocked DBContext

As we know DBContext in Entity Framework representing database entities is an auto-generated code created and customized using Scaffolding commands in Entity Framework tools.

Create a mocked DBContext instance using the Options Object created in the first step above.

//// Create mocked Context by seeding Data as per Schema///
            using (var context = new EmployeeContext(options))
            {
                context.Employee.Add(new Employee
                {
                    EmployeeId = "12345",
                    Country = "USA",
                    State = "NY",
                    Address = "Test1",
                    ZipCode = "121312"
                });
                context.Employee.Add(new Employee
                {
                    EmployeeId = "345435",
                    Country = "UK",
                    State = "MS",
                    Address = "Test2",
                    ZipCode = "121356"
                });
                context.SaveChanges();
            }

In the above example, EmployeeContext is created using scaffolding commands as discussed in our Getting Started using the EFCore article.

The above setup now can be used for Unit Testing the DBContext used in the application.

Unit Testing DBContext with Repository

Please see below the sample code that uses the DBContext in the Repository class using Constructor injection.

Unit Test Entity Framework Core Repository

For complete code, please visit Entity Framework Repository Implementation in ASP.NET Core.

Below is the complete Unit Testing Code for testing DBContext within Repository Instance,

Mock and Unit Test Entity Framework Core with Repository

Do you see any improvements or suggestions to the above code?

References

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



2 thoughts on “Mock and Unit Test Entity Framework Core with Repository

Leave a Reply

Your email address will not be published. Required fields are marked *