有人可以为我提供一个好的 PHPUnit 模拟指南的引用吗? official documentation 中的那个好像不够详细我正在尝试通过阅读源代码来学习 PHPUnit,但我对匹配器、调用模拟器、 stub 返回等术语并不熟悉。
我需要了解以下内容:
1)如何期望对模拟对象的方法进行多次调用,但每次调用都返回不同的值集?
$tableMock->expects($this->exactly(2))
->method('find')
->will($this->returnValue(2)); // I need the second call to return different value
2)如何期望使用多个参数调用模拟对象的方法?
最佳答案
[注意:链接站点中的所有代码示例,点击链接以获得更详尽的解释。]
返回不同的值
(当前)PHPUnit 文档建议 using a callback或 onConsecutiveCalls()
:
$stub->expects($this->any())
->method('doSomething')
->will($this->returnCallback('str_rot13'));
$stub->expects($this->any())
->method('doSomething')
->will($this->onConsecutiveCalls(2, 3, 5, 7));
期望多个参数
with()
可能包含 multiple parameters :
$observer->expects($this->once())
->method('reportError')
->with($this->greaterThan(0),
$this->stringContains('Something'),
$this->anything());
测试多个调用
虽然不问,但在相关主题上(而不是在我能找到的 PHPUnit 文档中),您可以使用 at()
到 set expectations for multiple calls to a method :
$inputFile->expects($this->at(0))
->method('read')
->will($this->returnValue("3 4"));
$inputFile->expects($this->at(1))
->method('read')
->will($this->returnValue("4 6"));
$inputFile->expects($this->at(2))
->method('read')
->will($this->returnValue(NULL));
关于php - 关于 PHPUnit 模拟功能的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3047086/