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.

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

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

Implement In-Memory Database

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

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.

About the author