我正在编写 Zend Framework 应用程序并使用 PHPUnit 对其进行单元测试.总的来说,事情进展顺利,但是我在 PHPUnit 和代码覆盖率方面有一个小而烦人的问题 - 它有时告诉我没有测试特定行,我不知道如何强制测试它.>
例如,在下面的代码中,我启动了两个测试:一个是 GET 请求,一个是 POST 请求.测试通过,一切正常.然而,当我查看代码覆盖率时,它告诉我else"行没有被执行.
公共函数editAction(){如果 ($request->isPost()) {//做与POST相关的动作} 别的 {//做与GET相关的动作}}
有什么想法吗?作为一个附带问题,您是否通常坚持进行单元测试,直到获得 100% 的代码覆盖率?或者这真的不实用?
非常感谢...
只有注释的代码才是最重要的.如果有可能落到最后,块的右大括号将在代码覆盖率报告中显示为可执行文件.寻找您实际上并未测试的分支.
if ($request->isPost()) {如果 ($x <5) {返回'<';}elseif ($x > 5) {返回'>';}//你有 $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% 的代码覆盖率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!