如何模拟方法在第一次调用时返回值X,在休息调用时返回Y?
以下解决方案有效,但我不想写$Y
这么多次:
$o->expects($this->any())
->method('foo')
->will($this->onConsecutiveCalls($X, $Y, $Y, $Y, $Y, $Y));
以下解决方案每次都会返回$Y
:
$o->expects($this->any())
->method('foo')
->will($this->returnValue($Y));
$o->expects($this->at(0))
->method('foo')
->will($this->returnValue($X));
答案 0 :(得分:2)
您可以通过在PHPUnit的returnCallback
函数中使用匿名函数而不是onConsecutiveCalls
来执行此操作。但是,这只是代码行,而不仅仅是为每个返回值键入$ Y,所以如果在第一次调用需要返回之后每次调用doSomething,我只会使用以下版本相同的值任何次数:
class Example
{
function doSomething() { }
}
// within your test class
public function testConsecutiveCallbacks()
{
$counter = 0;
$stub = $this->createMock(Example::class);
$stub
->method('doSomething')
->will($this->returnCallback(function () use (&$counter) {
$counter++;
if ($counter == 1) {
return 'value for x';
}
return 'value for y';
}));
$this->assertEquals('value for x', $stub->doSomething());
$this->assertEquals('value for y', $stub->doSomething());
$this->assertEquals('value for y', $stub->doSomething());
$this->assertEquals('value for y', $stub->doSomething());
}