Getting Start with Entity Framework Core 3.1 – Part VII

Introduction:

This blog will give you the knowledge about Testing Entity framework Core and the benefits of using the in-memory database provider to write the test methods.

The key points on what you will do in testing Entity framework Core,

  • Validate your DbContext against the database.
  • Validate your business logic against the DbContext.
  • Validate your business logic that uses the dbContext and database.

As far as Test Driven Development (TDD) is concerned Testing Entity Framework is really important to validate the units/methods programmed using its member with the unit test methods.

This is a continuation of my last blog.

The testing can be done using Entity Framework provider like SQL database or in-memory database provider.

Create a First Test Method:

Step 1: Right click on the Solution and select Add-> New Project.

Step 2: Search for MS Test and select MSTest TestProject template from the wizard.

MS Test Project
Figure 1: MS Test Project

Step 3: Add the data and domain project reference to the test project.

Reference
Figure 2: Adding reference

Step 4: Since we are going to use Entity Framework Core in-memory provider, download and install Microsoft.EntityFrameworkCore.InMemory package using NuGet Manager.

NuGet Package Manager
Figure 3: NuGet Package Manager

Step 5: Add the unit test method

  [TestMethod]
        public void InMemoryAddEntityTest()
        {
            var builder = new DbContextOptionsBuilder();
            builder.UseInMemoryDatabase("UserInsert");
            using (var context = new AppDBContext(builder.Options))
            {
                var user = new User();
                context.Users.Add(user);
                Debug.WriteLine($"Before Save :{user.Id}");
                context.SaveChanges();
                Debug.WriteLine($"After Save:{user.Id}");
                Assert.AreNotEqual(0, user.Id);
              
            }
        }

From the above code you can observe,

  • The DBContextOptionsBuilder() is initialized, which is used to access the in memory database provider.
  • UseInMemoryDatabase is the extension method which can be accessed through the DBContextOptionBuilder object to establish the connection.
  • buider.Options is passed  as a parameter to the AppDbContext constructor to initialize the context.  

Make sure the AppDBContext constructor is defined in AppDBContext.cs class.

 public AppDBContext(DbContextOptions options) : base(options)
        {
         
        }

It is quite obvious the test method is used to test the Add User Entity, and finally by using the assert statement we are verifying the user id to check whether the new user is created using the Add entity method by saving the changes in context.

Run the test method and observe the output in test explore.  

Test Explorer
Figure 4: Test Explorer

As expected, the test result got passed.

Test Outcome
Figure 5: Test Outcome

From the test explorer result you can observe, before and after saving the entity the user Id is same, which is something unexpected, because the id will be updated only after using SaveChanges() method with SQL database provider but with in-memory database provider saves the data as a list in the memory and it knows how to increment the Id whenever the object is added to the context using Add().

By considering the work process of in-memory database, we can rewrite the test method to track the context.

[TestMethod]
    public void InMemoryAddEntityTest()
    {
        var builder = new DbContextOptionsBuilder();
        builder.UseInMemoryDatabase("UserInsert");
        using (var context = new AppDBContext(builder.Options))
        {
            var user = new User();
            context.Users.Add(user);               
            Assert.AreEqual(EntityState.Added, context.Entry(user).State);

        }
    }

The assert statement is used to check the context tracking state.

Benefits of using In-Memory provider:

  • Emulates RDBMS via In-memory list.
  • Handles the generic RDBM Scenarios.
  • Great alternatives for test mocks.

Summary:

I hope this blog really helps you to understand the Testing Entity Framework Core and the benefits of using the In-Memory Database provider to write the test methods.

Source Code – https://github.com/gowthamece/EFCore

Happy Coding!!!

gowthamk91

Leave a Reply

%d bloggers like this: