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

How to reach 100% code coverage with expectexception in PHPUnit

我正在测试,如果输入必须失败,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 (或任何其他覆盖类型)时,我有这个测试的最后一行,最后一行另一行类似的测试,都是unreachable/not-executed。我可以理解那些没有被执行,因为如果代码是正确的,这个测试的最后一行将永远不会被执行,因为

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

总会抛出异常,函数执行结束。那么,如何才能使我的 class 达到 100% 的覆盖率?

不,您不会得到 100%,因为指标不应该出现在您的测试中。 您应该在配置中使用 whitelist or blacklist,以省略此测试。

It is mandatory to configure a whitelist for telling PHPUnit which sourcecode files to include in the code coverage report.

<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% 的覆盖率。