dongtui8593 2018-10-17 11:00
浏览 38

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

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

The test works fine, but the coverage isn't 100% because the test can't access to the last line of validateRemove method:

enter image description here

What's the propper solution?

  • 写回答

1条回答 默认 最新

  • dsfew215211 2018-10-17 20:21
    关注

    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.

    If you want the 100% coverage, you need to create a test where $this->collection[$key] is set . 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.

    Mine is an example as I don't really know how do you use that piece of code!

    评论

报告相同问题?

悬赏问题

  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?