简体   繁体   English

PHPUnit和Guard子句,而不是100%的覆盖率

[英]PHPUnit and Guard Clause, not 100% coverage

I have this Guard: 我有这个卫队:

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

And the test: 和测试:

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

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

CategoryCollection remove method calls validateRemove method CategoryCollection删除方法调用validateRemove方法

The test works fine, but the coverage isn't 100% because the test can't access to the last line of validateRemove method: 该测试工作正常,但是覆盖率不是100%,因为该测试无法访问validateRemove方法的最后一行:

在此处输入图片说明

What's the propper solution? 什么是合适的解决方案?

That's happening because you are not testing both the branches of the function, in your test case the function breaks when you throw the exception so it's not technically finishing. 发生这种情况是因为您没有同时测试函数的两个分支,在测试用例中,当您引发异常时函数会中断,因此从技术上讲还没有完成。 You have tested half of the function, even if it's the only logic in there. 您已经测试了half的功能,即使它只是其中的唯一逻辑。

If you want the 100% coverage, you need to create a test where $this->collection[$key] is set . 如果你想100%的覆盖率,则需要建立在那里进行测试$this->collection[$key] 设置 In that case, I would suggest to change your function to something like 在这种情况下,我建议将您的功能更改为

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

    return true;
}

and then create another test that asserts true when you call validateRemove() and $this->collection[$key] is set . 然后创建另一个测试,当你调用断言真validateRemove()$this->collection[$key] 设置

Mine is an example as I don't really know how do you use that piece of code! 我的例子就是一个例子,因为我真的不知道如何使用这段代码!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM