Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework (code first) in memory database for unit testing

For unit testing purposes, is it possible to do this:

  • Have test data in some format (XML?) checked into source control
  • When unit tests are run, instantiate some kind of in memory database from this test data
  • Have EF run against this in memory database for the duration of the unit test run

?

We don't want our unit tests to rely on a specific external database being present, and in a specific state.

We also don't want to maintain two different "worlds" in our code and tests, the real world where EF runs against a real db and a fake work where our tests run against some kind of EF mock.

like image 454
pinkfloydhomer Avatar asked Aug 15 '12 11:08

pinkfloydhomer


People also ask

Should I use in-memory database for testing?

This database provider allows Entity Framework Core to be used with an in-memory database. While some users use the in-memory database for testing, this is generally discouraged; the SQLite provider in in-memory mode is a more appropriate test replacement for relational databases.

How do I use code first in Entity Framework Core?

Code-First is mainly useful in Domain Driven Design. In the Code-First approach, you focus on the domain of your application and start creating classes for your domain entity rather than design your database first and then create the classes which match your database design.

What is Entity Framework in-memory database?

Entity Framework Core allows you to store and retrieve data to and from an in-memory database. It's a quick and easy way to test your ASP.NET Core 6 web applications. Cerae / Getty Images. There are many reasons why you might want to use an in-memory database when working on ASP.NET Core 6 web applications.


1 Answers

Unit tests should not be dependent on any database. Any dependency on database (even in memory database) means you are doing integration tests and integration tests should be done against the real database you are going to use.

I'm not aware of any XML database for EF but even if it exists you are back in front of your requirement: We also don't want to maintain two different "worlds" in our code and test. Every database has its own EF provider created by different company. Even providers for MS SQL Server and MS SQL Server Compact Edition are different enough to make switching between them quite challenging.

What you should do:

  • Hide all EF usage behind some abstraction (that includes everything including Linq-to-entities queries) and mock this abstraction instead of EF for unit tests
  • Use integration tests against the real database implementation you want to use in production for testing the abstraction itself
like image 175
Ladislav Mrnka Avatar answered Nov 15 '22 05:11

Ladislav Mrnka