【发布时间】:2017-07-22 17:18:44
【问题描述】:
我有以下模拟对象:
$permutator = $this->getMockBuilder('PermutationClass',
array('get_permutation'))->disableOriginalConstructor()->getMock();
$permutator->expects($this->at(0))
->method('get_permutation')
->will($this->returnCallback(function($praram1) {
return true;
}));
$permutator->expects($this->at(1))
->method('get_permutation')
->will($this->returnCallback(function($praram1) {
return true;
}));
但是,我的经验是,如果由于某种原因“1”处的调用从未被执行,那么就不会报告关于从未满足期望的错误。
如果我添加以下代码:就在期望之前:
$permutator->expects($this->exactly(2))->method('get_permutation');
然后发生的情况是,如果从未调用给定的期望,则会报告错误。但是,这里发生的情况是,由于某种原因,这使得模拟对象的返回值为 NULL,因为我没有设置它。如果我这样设置:
$permutator->expects($this->exactly(2))->method('get_permutation')->will($this->returnValue("THIS SHOULD NEVER BE RETURNED"));
然后 this 成为该函数的所有预期方法调用的返回值。所以 at(0) 和 at(1) 确实被执行了(我设置了一些打印语句)但是返回值被这个覆盖了:
$permutator->expects($this->exactly(2))->method('get_permutation');
我设法通过以下方式获得预期的行为:
$permutator->expects($this->exactly(2))
->method('get_permutation')
->will( $this->onConsecutiveCalls(
$this->returnCallback(function($praram1) {
return true;
}),
$this->returnCallback(function($praram1) {
return false;
})
)
);
我的意思是,当我明确设定期望时,为什么模拟对象不会抱怨说 $this->at(1) 永远不会被调用?
【问题讨论】:
-
您确定没有调用该方法吗?我使用 $this->at() 做了一个简单的示例,如果该方法仅调用一次,则测试失败。我认为您的代码中还有其他内容。
标签: php unit-testing mocking phpunit