2012-02-16 47 views
3

我有以下功能:的XDebug和PHPUnit的代码覆盖率说100%,其实它不是

function foo($p) 
{ 
    if ($p == null) 
     throw new Exception('bla'); 
    if ($p == null) 
    { 
     throw new Exception('bla'); 
    } 
    [...] 
} 

我给这家功能测试不覆盖抛出异常的行。但是PHPUnit告诉我,第一个'throw'语句被覆盖,第二个不是。也许第一个被解释,但它不被执行。

因此,如果我没有达到100%,我不想得到'100%'的消息。

这是xDebug中的错误还是我可以配置xDebug/PHPUnit?

回答

5

xDebug的代码覆盖率度量是基于语句而不是基于行的。这意味着没有用大括号括起来的控制结构被视为单个语句。要让xDebug将throw行与if()测试分开,请将其与第二个语句中的括号括起来。

if ($p == null)     // statement 1 
    throw new Exception('bla'); // rest of statement 1 

if ($p == null) {     // statement 1 
    throw new Exception('bla'); // statement 2 
} 
+0

感谢您的解释。你知道xDebug是否支持分支或条件等其他覆盖方法? – user1027167 2012-02-16 09:27:55

+0

@ user1027167 xDebug在语句上工作,但仅提供线条基本覆盖信息 – edorian 2012-02-16 09:50:11

+0

User1026176,我计划添加分支/条件覆盖,但目前为止还没有时间。 – Derick 2012-02-17 10:06:23

2

这是因为XDebug的不能提供更好的数据,因为它是只知道声明的,而不是“行”和下PHPUnit文档中记载:

Code coverage analysis - Edge Cases

<?php 
// Due to how code coverage works internally these two lines are special. 
// This line will show up as non executable 
if(false) 
    // This line will show up as covered because it is actually the 
    // coverage of the if statement in the line above that gets shown here! 
    will_also_show_up_as_coveraged(); 

// To avoid this it is necessary that braces are used 
if(false) { 
    this_call_will_never_show_up_as_covered(); 
} 

这同样适用于该$x ? $y : $z;构造。避免这种行为的唯一方法是添加花括号。

-1

当您必须修改源代码以克服您正在使用的工具的缺陷时,它非常糟糕。我们的PHP Test Coverage Tool不存在这个问题。

此外,如果您在同一行放置多个语句,我们将单独跟踪它们。我相信,如果覆盖该行中第一条语句的任何部分,XDebug会将“行”标记为覆盖。我相信它甚至会为以下这样做:

if (...) { .... } 

所以你会得到“假”报道报道了通过控制条件块,即使条件始终为false。