Unit Testing Data Access Layer in ASP.NET MVC 5 / Web API 2

asp.net-mvc-web-apiasp.net-mvc5cunit testingunit-of-work

Let's say I have IRepository interface implemented by Repository class(uses database context to implement IRepository methods). And IUnitOfWork interface implemented by UnitOfWork class using IRepository.

My questions are:

1) Should I unit test Repository on it's own?(have no idea how, because it uses database context and I don't know if it is good practice to mock database context?)

2) Will it be enough if I mock IRepository and only test UnitOfWork?

Best Answer

Should I unit test Repository on it's own?

I don't think there's much point. A Repository is supposed to act as a layer of abstraction between your business logic and the database, so by the time you mock the database for testing purposes, all that's left to test is the Repository's API endpoints (a test that I would regard as "uninteresting", and already covered by integration tests anyway).

Will it be enough if I mock IRepository and only test UnitOfWork?

Of course, depending on what you consider "enough." This is the appropriate place to mock a business operation, in my opinion, since the expected values are those required of your repository mock, and not those of a database (which would require an integration test).

To put it another way, your repository is already expected to return the "correct" value. If you're not sure about that, then include some integration tests for your repository (wired up with the proper data-source) to make sure.