问题在 中PHP
,但适用于使用该xUnit
框架的任何语言。
我想要一个模拟,期望对方法进行 140 次调用jump
。
我需要验证,至少有一次以 500 作为参数的调用。
我不在乎是否所有呼叫都是 500,但我至少需要一个以 500 呼叫的呼叫。
$mock = $this->getMock('Trampoline', ['jump']);
$mock->expects($this->atLeastOnce())
->method('jump')
->with($this->equalTo(500))
->will($this->returnValue(true));
$sportsman->setTramploine($mock);
$sportsman->jumpToRandomHeights($times = 140); // this calls Trampoline->jump
// I need to verify the sportsman had jumped
// to the height of 500 at least once out of the 140 jumps he is performing
在当前代码中,第一次调用后测试失败,jump
因为第一次调用的值不同500
,这意味着atLestOnce
这里只表示应该调用该方法,而不是在其他调用中以特定值调用它。
解决方案
缺少的信息是在with
. 感谢edorian在下面的回答,结果如下:
$testPassed = false;
$checkMinHeight = function ($arg) use(&$testPassed)
{
if($arg === 500)
$testPassed = true;
// return true for the mock object to consider the input valid
return true;
}
$mock = $this->getMock('Trampoline', ['jump'])
->expects($this->atLeastOnce())
->method('jump')
->with($checkMinHeight)
->will($this->returnValue(true));
$sportsman->setTramploine($mock);
$sportsman->jumpToRandomHeights($times = 1000); // this calls Trampoline->jump
// I need to verify the sportsman had jumped
// to the height of 500 at least once out of the 1000 jumps he is performing
$this->assertTrue($testPassed, "Sportsman was expected to
jump 500m at least once");