对于下面的代码,
$mockObject->expects($this->at(0))
->method('search')
->with($searchConfig)
->will($this->returnValue([]));
此行将自动做出断言确保当它调用方法时search
它必须包含$searchConfig
参数。在这种情况下,我们必须提供完全匹配的$searchConfig
但有时如果它是一个数组或一个对象,那就很难了。
有没有可能的方法让 PHPUnit 调用某个特定的方法来断言它包含我们想要的传入方法的参数?
例如,我可以创建闭包函数来断言如下,而不是使用->with()
method
function ($config){
$this->assertFalse(isset($config['shouldnothere']));
$this->assertTrue($config['object']->isValidValue());
}
您可以使用->with($this->callback())
并传入一个闭包以对参数执行更复杂的断言。
来自PHPUnit 文档 http://phpunit.de/manual/current/en/test-doubles.html#test-doubles.mock-objects.examples.SubjectTest.php
callback() 约束可用于更复杂的参数
确认。此约束将 PHP 回调作为唯一的约束
争论。 PHP 回调将接收要验证的参数:
它唯一的参数,如果参数通过则应返回 TRUE
验证,否则为 FALSE。
例 10.13:更复杂的参数验证
getMock('Observer', array('reportError'));
$observer->expects($this->once())
->method('reportError')
->with($this->greaterThan(0),
$this->stringContains('Something'),
$this->callback(function($subject){
return is_callable(array($subject, 'getName')) &&
$subject->getName() == 'My subject';
}));
$subject = new Subject('My subject');
$subject->attach($observer);
// The doSomethingBad() method should report an error to the observer
// via the reportError() method
$subject->doSomethingBad();
} } ?>
所以你的测试将变成:
$mockObject->expects($this->at(0))
->method('search')
->with($this->callback(
function ($config){
if(!isset($config['shouldnothere']) && $config['object']->isValidValue()) {
return true;
}
return false;
})
->will($this->returnValue([]));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)