【问题标题】:PHPUnit's code coverage does not cover executed methodPHPUnit 的代码覆盖率不包括执行的方法
【发布时间】:2019-08-13 23:19:40
【问题描述】:

对于可能错误地使用术语,我提前道歉。

我目前正在试验单元测试,以便将它们应用到我的工作中,但现在我遇到了一个问题,如果有的话。

在要测试的对象中执行了一个方法,尽管该方法已执行并且测试成功通过,但代码覆盖率并未将其标记为已测试。

我已经尝试过这可能是由于方法的可见性(它受保护)还是作为参数传递的回调可能通过更改可见性和参数而导致此“错误”,但这并没有似乎不是原因。

我使用以下设置

  • php-code-coverage 6.1.4
  • PHP 7.1.10
  • Xdebug 2.6.1
  • PHPUnit 7.5.7

以下代码段调用extend方法并传递一个匿名函数。

$this->values[$key] = $this->extend($key, function ($previous, ContainerInterface $container) use ($extensionFactory) {
    return call_user_func($extensionFactory, $container, $previous);
});

这是执行上述方法的测试

public function testContainerRegistersExtensions()
{
    /** mocking provider... */

    $this->assertEquals(['foo', 'bar'], (new Container([$provider]))->get('value'));
}


如下图片代码sn-ps中可以看到(我的信誉不允许使用图片),代码标记为覆盖(绿色),但方法extend不是(红色),虽然它是在测试期间执行的:

$this->values[$key] = $this->extend($key, function ($previous, ContainerInterface $container) use ($extensionFactory) {
    return call_user_func($extensionFactory, $container, $previous);
});
protected function extend($id, $callable)
{  
    $factory = $this->values[$id];

    $extended = function (ContainerInterface $container) use ($callable, $factory) {
    # if the entry to extend is not a callable, we pass it as is
    $previous = is_callable($factory) ? $factory($container) : $factory;
        return $callable($previous, $container);
    };

    $this->values[$id] = $extended;

    return $this->values[$id];
}


执行测试后的结果如下
PHPUnit 7.5.7 by Sebastian Bergmann and contributors.


Time: 260 ms, Memory: 6.00 MB

OK (11 tests, 12 assertions)

Generating code coverage report in HTML format ... done

现在我想知道我是否忘记了什么或做错了什么,或者这可能是一个错误?

【问题讨论】:

    标签: php phpunit code-coverage


    【解决方案1】:

    看来我找到了解决方案。关于注释的 PHPUnit 文档说:

    @covers 注解可以在测试代码中用于指定测试方法要测试的方法

    PHPUnit 7.5 Documentation - Annotations

    所以如果我在 PHPDoc 中指定一个@covers 标签,相应的方法也会被覆盖(并且只覆盖实际执行的部分)。这不是自动发生的,有点遗憾,但也许这是故意的。


    我的测试现在看起来像这样

    /**
     * @covers \<Namespace>\Container::register
     * @covers \<Namespace>\Container::extend
     * @covers \<Namespace>\Container::get
     */
    public function testContainerRegistersExtensions()
    {
        /** mocking provider... */
    
        $this->assertEquals(['foo', 'bar'], (new Container([$provider]))->get('value'));
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-15
      • 1970-01-01
      • 2022-11-08
      • 1970-01-01
      • 2012-05-04
      • 2012-08-04
      • 2012-05-07
      • 2012-04-27
      • 2017-09-01
      相关资源
      最近更新 更多