pinkfloydhomer
pinkfloydhomer

Reputation: 905

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

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

?

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.

Upvotes: 5

Views: 2657

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364389

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

Upvotes: 6

Related Questions