5

Can I somehow update shouldReturn value for specific shouldReceive?

For example I have several tests that have use one return value, and only one that uses some other return value.

So I have put this in setUp:

$this->someDependency->shouldReceive('someMethod')->andReturn(0);

If I put this in that specific test case:

$this->someDependency->shouldReceive('someMethod')->andReturn(1);

It will be ignored and 0 will be returned.

I "fixed" this moving mocking to all tests and removing from setUp. But I don't like that code duplication.

Ivan Toncev
  • 532
  • 5
  • 15
  • which is the discriminator to determine when return 1 instead of 0? Is possilbe by method argument data? If yes check the `with()` method – Matteo Nov 20 '15 at 09:58
  • 1
    Actually I am calling this method without arguments. This dependency is doctrine repository, and this count method, that is why I can have more than one value regardless the arguments. – Ivan Toncev Nov 20 '15 at 10:07
  • Have you tried to use the `andReturn(value1, value2, ...)` method as can be found in the [Mockery docs](http://docs.mockery.io/en/latest/reference/expectations.html)? – Fredrik Schöld Dec 01 '15 at 09:22
  • Than way my unit tests would be really dependent on each other. – Ivan Toncev Dec 01 '15 at 13:03
  • Maybe if instead of hardcoding return values as "0" and "1" you could have a global variable for the return value that is set once in the setup method and then updated in the test case that should have a different return value? – Fredrik Schöld Dec 03 '15 at 10:16

1 Answers1

2

This is mostly a matter of style. You can easily create a 'default' set of mocks in a helper function that is called by the test, and then a more explicit alternate version that sets them up differently.

You could also, in that helper, have a function parameter for a given value to return from a specific mock.

Some people believe that each test should be entirely independent from each other, other than some very common setup, and should do everything within itself. This does make it explicit as to what is going on (which very clear, and obvious what is going on) - but at a potential cost of code duplication. That is your choice however, if you prefer to not repeat yourself too much.

Alister Bulman
  • 34,482
  • 9
  • 71
  • 110
  • Thanks Alister, you are right about independent tests. But maybe there is a way to update shouldReceive in mockery, that's why I am not marking this answer as accepted. – Ivan Toncev Dec 01 '15 at 13:08