是否可以通过这种方式配置 PHPUnit 模拟?
$context = $this->getMockBuilder('Context')
->getMock();
$context->expects($this->any())
->method('offsetGet')
->with('Matcher')
->will($this->returnValue(new Matcher()));
$context->expects($this->any())
->method('offsetGet')
->with('Logger')
->will($this->returnValue(new Logger()));
我使用 PHPUnit 3.5.10,当我请求 Matcher 时它失败,因为它需要“Logger”参数。
这就像第二个期望正在重写第一个期望,但是当我转储模拟时,一切看起来都很好。
遗憾的是,默认的 PHPUnit Mock API 无法实现这一点。
我可以看到两个选项可以让你接近这样的事情:
使用 ->at($x)
$context = $this->getMockBuilder('Context')
->getMock();
$context->expects($this->at(0))
->method('offsetGet')
->with('Matcher')
->will($this->returnValue(new Matcher()));
$context->expects($this->at(1))
->method('offsetGet')
->with('Logger')
->will($this->returnValue(new Logger()));
这可以正常工作,但您测试的内容超出了应有的范围(主要是首先使用匹配器调用它,这是一个实现细节)。
此外,如果您对每个函数进行多次调用,这也会失败!
接受两个参数并使用 returnCallBack
这是更多的工作,但效果更好,因为您不依赖于调用的顺序:
工作示例:
<?php
class FooTest extends PHPUnit_Framework_TestCase {
public function testX() {
$context = $this->getMockBuilder('Context')
->getMock();
$context->expects($this->exactly(2))
->method('offsetGet')
->with($this->logicalOr(
$this->equalTo('Matcher'),
$this->equalTo('Logger')
))
->will($this->returnCallback(
function($param) {
var_dump(func_get_args());
// The first arg will be Matcher or Logger
// so something like "return new $param" should work here
}
));
$context->offsetGet("Matcher");
$context->offsetGet("Logger");
}
}
class Context {
public function offsetGet() { echo "org"; }
}
这将输出:
/*
$ phpunit footest.php
PHPUnit 3.5.11 by Sebastian Bergmann.
array(1) {
[0]=>
string(7) "Matcher"
}
array(1) {
[0]=>
string(6) "Logger"
}
.
Time: 0 seconds, Memory: 3.00Mb
OK (1 test, 1 assertion)
我用过$this->exactly(2)
在匹配器中表明这也适用于计算调用次数。如果你不需要把它换成$this->any()
当然会起作用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)