Faking Database Interactions with Entity Framework Core

Learn how to use a fake implementation of a relational database for automated testing.

Entity Framework (EF) Core and other object-relational mappers (ORMs) available on .NET allow us to fake the database functionality using in-memory databases. This enables us to use the same code in our application as we would use for a real database. In contrast, we don’t have to use any real database connection in unit tests, which makes our tests fast.

In the context of automated testing, this technique is called faking. Unlike stubbing and mocking, faking allows us to interact with the object the same way we would interact with a real object, (i.e., the object exhibits a realistic behavior and returns realistic responses). The object can even keep its state, which certain interactions can modify.

A fake can be represented by an external object outside our code. For example, instead of connecting to a real banking API, we would connect to a sandbox environment that behaves just like it without affecting any real data. Or, as with the case of faking a database, there is a slight configuration difference between the test code and the actual application code.

Faking a database by substituting it with an in-memory version has many advantages over stubbing or mocking. In particular, it allows us to emulate the entire database behavior—including deletion, insertion, querying, etc.—while only writing a small amount of setup code. Similarly, we don't need to set up every method or write any stub logic.

Setting up an in-memory database

Let’s see how faking a database works with the help of the following playground:

Get hands-on with 1200+ tech skills courses.