Search code examples
unit-testingnunitmoqrhino-mocks

Mocking and Repository / Service layers in C#


I am trying to write some unit tests for testing my service layer which I am doing well I think, the service layer as a dependency on a repository so am mocking a repository using RhinoMocks, so I am testing the Service layer "WITHOUT" hitting the database which is great.

Now I need to test my repository layer, this has a direct connection to a database so I have to test it don't i? I have no other option but to test it?

If I test another implementation of the Repository that doesn't hit the database then this is no testing my implementation.

I have managed to mock out all lower layers so anything that depended on code that takes a while to run ie. The repository, then I mocked this out. The result is that all my tests for layers below the repository complete fast and do not hit the database.

The problem is what do I now do with the repository. I have to test it but it has a dependency on a SQL database.


Solution

  • Well, the general answer goes like this. I would write unit tests that verifies the logic of the repository layer and break out the sql dependency in a new class and mock it in the tests of the repo. If the repository layer contains only a sql connection and no logic there is nothing to unit test in my opinion. Then you are more suitable with integration tests with the database connected.