Using an in-memory database provider for test methods

In this post, I will be using an in-memory database provider for test methods and their benefits. Using an in-memory database provider when writing test methods is one of the advantages of testing Entity Framework Core.

In testing Entity Framework Core, the following points will be important:

  • The DbContext needs to be validated against the database.
  • Verify the validity of your business logic against the DbContext.
  • Verify the business logic using the database and dbContext.

Testing Entity Framework is crucial for validating the units and methods developed by TDD’s members with unit test methods.

I am continuing my last blog post.

A SQL database or an in-memory database can be used as the testing environment.

First, create a test method:

Adding a new project is as simple as clicking Add->New Project from the Solution dropdown menu.

In the wizard, choose the MSTest TestProject template under MS Test.

Using an in-memory database provider for test methods

Add the domain and data projects to the test project.

Using an in-memory database provider for test methods

With NuGet Manager, download and install Microsoft.EntityFrameworkCore.InMemory package since we are using Entity Framework Core in-memory provider.

Using an in-memory database provider for test methods

Unit tests need to be added

 [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);
              
            }
        }

As you can see from the above code,

  • An in-memory database provider is accessed via the DBContextOptionsBuilder().
  • A connection to an in-memory database can be established by using the UseInMemoryDatabase extension method.
  • AppDbContext is initialized by passing a parameter called builder.Options to its constructor.  

In the AppDBContext.cs class, ensure that the AppDBContext constructor is defined.

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

We use the test method to test the Add User Entity, then using the assert statement to verify that the user was created.

Observe the output in test explore after running the test method.  

Using an in-memory database provider for test methods

Test results were passed as expected.

Using an in-memory database provider for test methods

This is somewhat surprising, because SQL database providers only update the ID when they use SaveChanges() to save changes, so there is no difference between before and after saving the entity. An object’s Id is incremented whenever an object is added to a list if the data is stored in memory with in-memory database providers.

The test method can be rewritten to track the context by considering the work process of an in-memory database.

[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);

        }
    }

Checking the context tracking state is done with the assert statement.

There are several benefits to using in-memory providers:

  • A list in memory simulates an RDBMS.
  • Scenarios that are generic to RDBM are handled.
  • Mock tests are a great alternative to actual tests.

Conclusion:

I hope this blog helps you understand why you should use the In-Memory Database provider when writing test methods for the Testing Entity Framework Core.

Leave a Comment