Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way of testing Repositories which use DbContext

In my projects, I follow repository pattern in order to easily unit test my ASP.NET MVC app. This allows me to easily mock the objects.

However, I am not testing the Repository logic by this way at all.

For instance, see the below blog post:

How to Work With Generic Repositories on ASP.NET MVC and Unit Testing Them By Mocking

This is what I do and how I test my ASP.NET MVC App.

What do you think the best way of testing repositories which uses DbContext class to reach out the data?

  • Directly getting data from database? (I think this would be the worst but I wonder your thopughts)
  • Should I create a fake databse and fill it in with dummy data and point EF to connect that database?

And any other approach you might suggest.

EDIT:

I am using EF 4.2 here.

like image 800
tugberk Avatar asked Dec 24 '11 09:12

tugberk


People also ask

Do we need repository pattern with Entity Framework?

The single best reason to not use the repository pattern with Entity Framework? Entity Framework already implements a repository pattern. DbContext is your UoW (Unit of Work) and each DbSet is the repository. Implementing another layer on top of this is not only redundant, but makes maintenance harder.

What is mock repository?

Mocking is a way to encapsulate your unit tests. If you want to test a service method you are not interested if the repository is working. For this you will write repository tests. Therefore you mock the repository call and tell which result should be returned to test your method in all possible situation.


1 Answers

The respository is you entry point to the database so the only way to test it is to use integration test and work on a test database. You can use transactional tests where each test will setup transaction and rollback at the end of the test to keep test data same for all tests.

like image 195
Ladislav Mrnka Avatar answered Oct 20 '22 17:10

Ladislav Mrnka