Martin
Martin

Reputation: 24318

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.

Upvotes: 3

Views: 973

Answers (3)

tallseth
tallseth

Reputation: 3665

You certainly can test your repository layer without talking to a database. Most ADO.net classes are mockable, if you are careful about how you create them and you are careful to couple to interfaces instead of concretions. Unfortunately, ADO.net was created before mocking was a very popular practice, and it is still a bit of a pain to do.

The real question in my mind is whether you should try to mock them. The benefits of mocking are twofold: they run faster, and they force you to encapsulate more details about your database (making it easier to switch out db technologies, if you ever want to do it). The benefits of functional tests are that they also test your database layer (stored procedures, etc), they are arguably easier to write, and they are easier to maintain in the sense that if a db change is made, integration tests notice automatically, instead of you hunting the mocked out tests down.

I would say the "best" approach would be to test them both with moqs and with the real database, since this gives you the best of both worlds. However, it is quite costly of course.

Upvotes: 1

Tobias Nilsson
Tobias Nilsson

Reputation: 512

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.

Upvotes: 7

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236268

Thus mocking code you don't own is a bad practice, I think best option for you is to test repositories via acceptance/integration tests

Upvotes: 1

Related Questions