phpunit: method serves different output based argument
I had the issue that my test-double sent incorrect values when invoked with specific arguments.
It returned null
on every request.
First I thought this mock would return null
on every call, but that’s not the case. Then I stumbled on this post on StackOverflow https://stackoverflow.com/questions/12748607/phpunits-returnvaluemap-not-yielding-expected-results.
The solution: the map-array needs all parameter-values listed in every element. Even the optional ones. I had to add null
values for the optional parameters!
use returnValueMap
method to map the received arguments to an array.
function myMethod($name, $optional=null){ // ... } // Define which value need to be returned when // called with argument 'x' // first element is argument 'x'; the argument passed, // 2nd element is the optional argument of the function // 3d element is what will be returned by the test-double $map = [ ['value1', null, $valueToReturn1], ['value2', null, $valueToReturn2] ]; $request->expects($this->any()) ->method('getRepository') ->will($this->returnValueMap($map)); $request->getRepository('value1'); // will return $valueToReturn1
Without the null
added to it, it won’t work.
Example for my mock with Symfony. This will return the relevant repository on a request for method getRepository
and with returnvalues for arguments AppBundle:Valuation
and AppBundle:ObjectInvolvement
.
$map = [ ['AppBundle:Valuation', $valuationRepository], ['AppBundle:ObjectInvolvement', $objectInvolvementRepository] ]; $entityManager->expects($this->any()) ->method('getRepository') ->will($this->returnValueMap($map));