如何在PHPUnit中使用expectexception达到100%的代码覆盖率

时间:2017-07-04 07:09:18

标签: php phpunit code-coverage

我正在测试,如果输入必须失败,handleMatchResults将抛出RouteNotFoundException。这是实际测试的代码:

public function test_not_found_match_throws_NotFoundException()
{
    $this->expectException(RouteNotFoundException::class);
    $request = $this->prophet->prophesize(ServerRequest::class);
    $this->router->handleMatchResults([0, []], $request->reveal());
}

一切都按预期进行,我的测试通过,但是,当我运行phpunit --coverage-text(或任何其他覆盖类型)时,我有这个,测试的最后一行,以及另一个类似测试的最后一行,无法访问/未执行。我可以理解那些没有被执行,因为如果代码是正确的,那么这个测试的最后一行不会被执行,因为

$this->router->handleMatchResults([0, []], $request->reveal());

将始终抛出异常并且函数的执行将结束。那么,我如何达到我班级的100%覆盖率?

1 个答案:

答案 0 :(得分:1)

不,你不会得到100%,因为度量标准不应该在你的TEST上。 您应该在配置中使用whitelist or blacklist来省略此测试。

  

必须配置一个白名单来告诉PHPUnit   源代码文件包含在代码覆盖率报告中。

<filter>
  <whitelist processUncoveredFilesFromWhitelist="true">
    <directory suffix=".php">/path/to/files</directory>
    <file>/path/to/file</file>
    <exclude>
      <directory suffix=".php">/path/to/files</directory>
      <file>/path/to/file</file>
    </exclude>
  </whitelist>
</filter>

您的代码将标记为handleMatchResults并执行throw。在其他测试中,您将使用此功能执行正面场景。

这样你应该有100%的覆盖率。