Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting different consecutive values on php mockery

TLDR; How do I get value1 first time and value2 the second time when calling the mockery shouldReceive('method)` with same parameter?

Lets say I have an $order object that implements this signature with a method getState().

interface Order {
    public function getState();
}

Now, on unit tests, I want to use mockery to get mock the $order object so that when getState is called

  • 1st time it returns initialized value
  • 2nd time it returns processing value

Well, I know it could have been done for the case where the return value is different based on parameters using ...->with($param1)->andReturn....

Plus withConsecutive seems to be the way to do on phpunit. How do I implement this on the mockery? I could not found anything about it on mockery doc nor on stackoverflow.

Thanks.

like image 386
Bikal Basnet Avatar asked Aug 26 '26 23:08

Bikal Basnet


2 Answers

From the section Declaring Return Value Expectations:

It is possible to set up expectation for multiple return values. By providing a sequence of return values, we tell Mockery what value to return on every subsequent call to the method:

$mock = \Mockery::mock('MyClass');
$mock->shouldReceive('name_of_method')
    ->andReturn($value1, $value2, ...)

The first call will return $value1 and the second call will return $value2.

like image 69
Matteo Avatar answered Aug 28 '26 13:08

Matteo


I think it can be done using the help of array_shift inside mockery's andReturnUsing method

$orderStates = [
    'intially-order-was' => 'initialized',
    'then-order-becomes' => 'processing'
];

$order
    ->shouldReceive('getState')
    ->andReturnUsing(function() use (&$orderStates) {
        return array_shift($orderStates);
});
like image 22
Bikal Basnet Avatar answered Aug 28 '26 14:08

Bikal Basnet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!