如何使用PHPUnit获得100%的代码覆盖率 [英] How to get 100% Code Coverage with PHPUnit

查看:219
本文介绍了如何使用PHPUnit获得100%的代码覆盖率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个Zend Framework应用程序,并使用PHPUnit对其进行单元测试.总的来说,事情进展得很顺利,但是PHPUnit和代码覆盖率却有一个小而烦人的问题-它有时会告诉我未测试特定的行,而且我不知道如何强制对其进行测试.

例如,在下面的代码中,我启动了两个测试:一个带有GET请求的测试,一个带有POST请求的测试.测试通过了,一切都很好.但是,当我看一下代码覆盖率时,它表明没有执行'else'行.

public function editAction()
{        
    if ($request->isPost()) {
        // do actions related to POST
    } else {
        // do action related to GET
    }
}

有什么想法吗?作为附带问题,您通常会坚持不懈地进行单元测试,直到获得100%的代码覆盖率为止?还是这不是很实际?

非常感谢...

解决方案

您唯一要注释的代码很重要.如果可能的话,在代码覆盖率报告中,块的右大括号将显示为可执行文件.寻找您未实际测试的分支.

if ($request->isPost()) {
    if ($x < 5) {
        return '<';
    }
    elseif ($x > 5) {
        return '>';
    }
    // Do you have a test for $x == 5?
}

对于100%代码覆盖率的目标,我完全同意Bill.对于我编写的某些框架类,我将努力做到100%,但我知道那并不意味着我已经真正测试了所有可能性.通常,当我发现自己为达到100%的覆盖率而过度努力时,可能是强迫症发作了.:)

就这样. . .一 . . .更多的 . . .测试 . .

I am writing a Zend Framework application and unit testing it with PHPUnit. In general, things are going swimmingly however I have a small, but annoying issue with PHPUnit and code coverage - it sometimes tells me that a particular line is not tested, and I don't know how to force it to be tested.

In the following code, for example, I launch two tests: one with a GET request, one with a POST request. The tests pass, and that's all fine. When I look at the code coverage, however, it shows me that the 'else' line is not executed.

public function editAction()
{        
    if ($request->isPost()) {
        // do actions related to POST
    } else {
        // do action related to GET
    }
}

Any ideas? As a side issue, do you usually persevere with unit tests until you get 100% code coverage? Or is this not really practical?

Thanks muchly...

解决方案

The code you have only comments for is what matters. The closing brace of a block will be shown as executable in the code coverage report if it's possible to fall through to the end. Look for a branch that you aren't actually testing.

if ($request->isPost()) {
    if ($x < 5) {
        return '<';
    }
    elseif ($x > 5) {
        return '>';
    }
    // Do you have a test for $x == 5?
}

As for the 100% code coverage goal, I agree wholeheartedly with Bill. For some framework classes that I write I will strive to make 100%, but I know that doesn't mean I've truly tested every possibility. Often, when I find myself working overly hard to achieve 100% coverage, it's probably OCD kicking in. :)

Just . . . one . . . more . . . test . . .

这篇关于如何使用PHPUnit获得100%的代码覆盖率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆