gre*_*emo 7 php phpunit unit-testing
部分测试科目:
class AddOptionsProviderArgumentPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
if(!$container->hasDefinition('gremo_highcharts')) {
return;
}
if(!$container->hasParameter('gremo_highcharts.options_provider')) {
return;
}
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
我想断言:
hasDefinition()
使用参数'gremo_highcharts'调用将返回 false
process()
返回,即不会调用其他方法一种解决方案是断言后续调用hasParameter()
:
public function testProcessWillReturnIfThereIsNoServiceDefinition()
{
$container = $this->getMockedContainerBuilder();
$pass = new AddOptionsProviderArgumentPass();
$container->expects($this->once())
->method('hasDefinition')
->with($this->equalTo('gremo_highcharts'))
->will($this->returnValue(false));
// Expects that hasParameter() is never invoked
$container->expects($this->never())
->method('hasParameter');
$pass->process($container);
}
Run Code Online (Sandbox Code Playgroud)
但它似乎不是一个优雅的解决方案.
小智 2
这是特例吗?如果是这样,您可以将第一个返回(为什么要返回 void ?)更改为抛出特定的异常。然后使用 PHPUnit 验证是否确实捕获了该特定异常。
编辑:同样使用 Phake,您可以在测试结束时编写类似的内容:(类似于使用 PHPUnit 模拟对象调用 ->never() )
Phake::verify($container, Phake::times(0))->hasParameter();
Run Code Online (Sandbox Code Playgroud)
这在存根方法调用和验证方法(存根或未存根)已被调用之间产生了区别。