在 php 嘲笑中获得不同的连续值
Getting different consecutive values on php mockery
TLDR;
如何在使用相同参数调用嘲弄 shouldReceive('method
)` 时第一次获得 value1
并第二次获得 value2
?
假设我有一个 $order
对象,它使用方法 getState()
实现了这个签名。
interface Order {
public function getState();
}
现在,在单元测试中,我想使用模拟来模拟 $order
对象,以便在调用 getState
时
- 第一次 returns
initialized
值
- 第二次return秒
processing
值
好吧,我知道在 return 值因使用 ...->with($param1)->andReturn...
.
的参数而不同的情况下是可以做到的
加 withConsecutive
似乎是 phpunit
的方法。我如何在嘲弄中实现这一点?我在 mockery doc 和 Whosebug 上都找不到任何相关信息。
谢谢。
我认为可以在 mockery 的 andReturnUsing
方法中使用 array_shift
的帮助来完成
$orderStates = [
'intially-order-was' => 'initialized',
'then-order-becomes' => 'processing'
];
$order
->shouldReceive('getState')
->andReturnUsing(function() use (&$orderStates) {
return array_shift($orderStates);
});
来自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.
TLDR;
如何在使用相同参数调用嘲弄 shouldReceive('method
)` 时第一次获得 value1
并第二次获得 value2
?
假设我有一个 $order
对象,它使用方法 getState()
实现了这个签名。
interface Order {
public function getState();
}
现在,在单元测试中,我想使用模拟来模拟 $order
对象,以便在调用 getState
时
- 第一次 returns
initialized
值 - 第二次return秒
processing
值
好吧,我知道在 return 值因使用 ...->with($param1)->andReturn...
.
加 withConsecutive
似乎是 phpunit
的方法。我如何在嘲弄中实现这一点?我在 mockery doc 和 Whosebug 上都找不到任何相关信息。
谢谢。
我认为可以在 mockery 的 andReturnUsing
方法中使用 array_shift
的帮助来完成
$orderStates = [
'intially-order-was' => 'initialized',
'then-order-becomes' => 'processing'
];
$order
->shouldReceive('getState')
->andReturnUsing(function() use (&$orderStates) {
return array_shift($orderStates);
});
来自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.