【问题标题】:PHPUnit and Guard Clause, not 100% coveragePHPUnit 和 Guard Clause,不是 100% 覆盖
【发布时间】:2019-03-22 00:57:48
【问题描述】:

我有这个守卫:

protected function validateRemove($key)
{
    if (!isset($this->collection[$key])) {
        throw new CategoryCollectionBadItemException();
    }
}

还有测试:

/**
 * @test
 * @expectedException InfluenceDecision\Domain\Exception\Category\CategoryCollectionBadItemException
 */
public function removeMethodMustThrowExceptionWithInvalidKey()
{
    $this->categoryCollection->add(
        new Category(
            null,
            'test category'
        )
    );

    $this->categoryCollection->remove(1);
}

CategoryCollection remove 方法调用 validateRemove 方法

测试工作正常,但覆盖率不是 100%,因为测试无法访问 validateRemove 方法的最后一行:

正确的解决方案是什么?

【问题讨论】:

  • 覆盖率报告告诉你方法的右大括号未被覆盖?也许您需要一个提供有效集合密钥的测试。不过,我个人认为不值得在这方面投入时间,您已经涵盖了您想要涵盖的逻辑,而且 100% 的代码覆盖率基本上只是一个不错的徽章

标签: php phpunit code-coverage guard-clause


【解决方案1】:

发生这种情况是因为您没有测试函数的两个分支,在您的测试用例中,当您抛出异常时函数会中断,因此它在技术上并未完成。您已经测试了函数的half,即使它是其中唯一的逻辑。

如果你想要 100% 的覆盖率,你需要创建一个测试 $this->collection[$key] 设置。 在这种情况下,我建议将您的功能更改为类似

protected function validateRemove($key)
{
    if (!isset($this->collection[$key])) {
        throw new CategoryCollectionBadItemException();
    }

    return true;
}

然后创建另一个测试,当您调用validateRemove()$this->collection[$key] 已设置 时断言为真。

我是一个例子,因为我真的不知道你如何使用那段代码!

【讨论】:

    猜你喜欢
    • 2012-03-07
    • 2018-06-21
    • 1970-01-01
    • 2014-06-07
    • 2017-03-30
    • 1970-01-01
    • 2011-05-19
    • 2011-05-27
    • 2012-05-04
    相关资源
    最近更新 更多