I am trying to send a pre-calculated array of test cases into a mock to be returned on consecutive calls - similar to the map function. However it takes a list of arguments, not an array.
My array is already generated by a fixture-generator and may be of variable length.
What I want to do is something like this, but of course this causes it to return the entire array on the first call.
// In a test case:
$processorMock
->method('process')
->willReturnOnConsecutiveCalls(
$fixtureLoader->getProcessorScenarios() // how to explode this?
);
// class FixtureLoader pseudocode:
function getProcessorScenarios(){
return [
[ $param1, $param2, $param3 ], // case 1
[ $param1, $param2, $param3 ], // case 2
...
[ $param1, $param2, $param3 ], // case N
];
}
I want to destructure the returned array from the fixture loader, using list() or some var-args exploding language construct like "..." in other languages, but couldn't find anything native that worked.
I do have what feels like a hacky method, which I will post as an initial answer Q&A style. I want to know if it's the best method.
A friend suggested an alternative available in PHP 5.6 - the "splat" operator or elipsis (...) although it doesn't seem to have an official name in PHP, but is a form of destructuring like the "spread" operator in Javascript ES6.
While I haven't tested this (as my app is currently locked to PHP 5.4 due to environmental constraints), it should therefore work simply thus:
$processorMock
->method('process')
->willReturnOnConsecutiveCalls(
...$fixtureLoader->getProcessorScenarios()
);
This is definitely the sweeter alternative I was looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With