views:

24

answers:

1

I am mocking a repository that should have 1 entity in it for the test scenario. The repository has to return this entity based on a known id and return nothing when other ids are passed in.

I have tried doing something like this:

_myRepository.Expect(item => item.Find(knownId)).Return(knownEntity);
_myRepository.Expect(item => item.Find(Arg<Guid>.Is.Anything)).Return(null);

It seems however the second line is overriding the first and the repository always returns null. I don't want to mock all the different possible IDs asked (they could go up to hundreds) when the test scenario is only concerned with the value of one Id.

I understand that I can change the second line to be the negative of the first. However this would become more and more difficult (as well as ugly) if the repository has to return more than 1 entity for a test scenario.

A: 

It did work for me correctly. My guess is that you are searching for your known id more than once. Try changing the quoted lines to:

_myRepository.Stub(item => item.Find(knownId)).Return(knownEntity);
_myRepository.Stub(item => item.Find(Arg<Guid>.Is.Anything)).Return(null);

and let me know if it solves the issue.

Grzenio
Interesting. It works if I use Stub. But if I replace it with Expect (dynamic or static), it doesn't. What's the difference then?
Khash
The difference is that Expect be default sets the expectation that the method will be run only once, Stub on the other hand works always. You can change it for Expect: `_myRepository.Expect(item => item.Find(knownId)).Return(knownEntity).Repeat.Any();` (or similar syntax)
Grzenio
Also note that `Stub` only sets behavior, it does not set expectations. For example, if you want to make the assertion that your method was called with certain arguments then you'll have to call `AssertWasCalled(x=>x.Find(someId));` at the end of your test
Wim Coenen