Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mock your repositories?

I've use Moq to mock my repositories. However, someone recently said that they prefer to create hard-coded test implementations of their repository interfaces.

What are the pros and cons of each approach?

Edit: clarified meaning of repository with link to Fowler.

like image 831
Mike Scott Avatar asked Dec 11 '08 15:12

Mike Scott


People also ask

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.

What is repository in unit test?

Instead of depending on an external data source, we call the repository, which is a logic layer and hence very easy to mock. This is our favorite approach to creating unit tests for our applications, and we're going to implement an example in a minute.


1 Answers

I generally see two scenarios with repositories. I ask for something, and I get it, or I ask for something, and it isn't there.

If you are mocking your repository, that means you system under test (SUT) is something that is using your repository. So you generally want to test that your SUT behaves correctly when it is given an object from the repository. And you also want to test that it handles the situation properly when you expect to get something back and don't, or aren't sure if you are going to get something back.

Hard-coded test doubles are ok if you are doing integration testing. Say, you want to save an object, and then get it back. But this is testing the interaction of two objects together, not just the behavior of the SUT. They are two different things. If you start coding fake repositories, you need unit tests for those as well, otherwise you end up basing the success and failure of your code on untested code.

That's my opinion on Mocking vs. Test Doubles.

like image 151
NerdFury Avatar answered Sep 29 '22 14:09

NerdFury