Setup In-Memory Database For Testing In .NET Core

In this post you will learn how to setup in-memory database for testing in .net core applications.

Introduction

Whether we like it or not, we all face the need to test our code. Whether it is your Web API or it is a business logic layer, you will more than often find yourself writing tests in your .net core application. Since we do not write tests against a LIVE production database, it is important to test in a safer environment.

For this purpose, we need to setup in-memory database for testing.

DecisionMentor app

Setup In-Memory DbContext

If you haven’t yet setup your entity framework database context, start here: Entity Framework Code First Approach With .NET Core.

Let’s say you have your DbContext ready and you have called it MyDbContext.

Now in your test project, create a class for initializing a test context. Call it “TestBootstrapper.cs

public class TestBootstrapper
    {
        /// <summary>
        /// Create an instance of in memory database context for testing.
        /// Use the returned DbContextOptions to initialize DbContext.
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public static DbContextOptions<MyDbContext> GetInMemoryDbContextOptions(string dbName = "Test_DB")
        {
            var options = new DbContextOptionsBuilder<MyDbContext>()
                .UseInMemoryDatabase(databaseName: dbName)
                .Options;

            return options;
        }
    }

The UseInMemoryDatabase comes from a EF core package. You should have this package included in your project beforehand.

<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="2.2.2" />

Implement In-Memory Database

Now, in your test classes, you can initialize a test db context like this:

[Given(@"I have phone number (.*) in the system")]
public void GivenIHavePhoneNumberInTheSystem(string number)
{
	using (var context = new TrueComDbContext(
		TestBootstrapper.GetInMemoryDbContextOptions("testDb")))
	{

		var testUser = new Login();
		testUser.FirstName = "test";
		testUser.LastName = "test";
		testUser.UserName = number;
		testUser.Password = "test";

		context.Logins.Add(testUser);
	}
}

Basically, we initialize the database context options by passing a database name. Use the in-memory database context options to create a context and use it to initialize your test data.

Important Points To Remember

When we setup in-memory database for testing in .net core applications, it is important to keep couple of things in mind.

  • Make sure to use same database names for same test scenario. If you use different names for initializing test data and for running test actions, you will not get the desired results!
  • Make sure to use different database names for different test cases. If not you will end up with multiple test cases accessing same in-memory database.

Wrapping Up

In this post we demonstrated how to setup in-memory database for testing. We created a TestBootstrapper that handled creating in-memory db context options. Using that we created test database contexts. We also looked at how we can avoid certain issues when using in-memory database with entity framework in .net core applications.