ezz*_*ron 4 php phpunit unit-testing mocking
使用PHPUnit,我正在使用 - > at()测试一系列方法调用,如下所示:
$mock->expects($this->at(0))->method('execute')->will($this->returnValue('foo'));
$mock->expects($this->at(1))->method('execute')->will($this->returnValue('bar'));
$mock->expects($this->at(2))->method('execute')->will($this->returnValue('baz'));
Run Code Online (Sandbox Code Playgroud)
我如何设置模拟,以便在上面的场景中,如果 execute()被调用四次或更多次,它会立即失败?我试过这个:
$mock->expects($this->at(3))->method('execute')->will($this->throwException(new Exception('Called too many times.')));
但是如果没有调用execute()四次,这也会失败.它需要立即失败,否则被测系统将产生自己的错误,这导致产生的错误消息不清楚.
我设法最终找到了解决方案.我使用了一个comUn $this->returnCallback()和传递PHPUnit匹配器来跟踪调用计数.然后你可以抛出一个PHPUnit异常,这样你也可以得到很好的输出:
$matcher = $this->any();
$mock
->expects($matcher)
->method('execute')
->will($this->returnCallback(function() use($matcher) {
switch ($matcher->getInvocationCount())
{
case 0: return 'foo';
case 1: return 'bar';
case 2: return 'baz';
}
throw new PHPUnit_Framework_ExpectationFailedException('Called too many times.');
}))
;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2000 次 |
| 最近记录: |