当我们代码测试覆盖率为的时候
作者:网络转载 发布时间:[ 2013/1/4 9:49:19 ] 推荐标签:
分支覆盖率的意思是:要遍历所有的if条件表达式可能的值。
我们用另外一个工具(eCobertura)来观察测试覆盖率,你对分支覆盖有点印象了。
对上面代码,我们用eCobertura统计的结果为:分支覆盖率50%,代码覆盖率

为了更好理解分支覆盖,我们再增加一个函数:
package test.unit;
public class Branch {
public String getValue(int condition){
String ret = null;
if (condition > 10){
ret = “true”;
}
return ret;
}
public String getValue(int x, int y){
String ret = null;
if (x > 0 && y > 0){
ret = “true”;
}
return ret;
}
}
测试函数:
package test.unit;
import junit.framework.TestCase;
public class TestBranch extends TestCase{
public void testBranch(){
Branch b = new Branch();
String real_val = b.getValue(20);
assertTrue(real_val.equals(“true”));
}
public void testGetValueXY(){
Branch b = new Branch();
String real_val = b.getValue(10, 10);
assertTrue(real_val.equals(“true”));
}
}
然后我们用eCobertrua测试,发现这个if分支有4条路径,只测试了两条。

为什么是四条路径?这个是之前说的,分支覆盖率会遍历所有的可能条件:x,y组合起来,是有四种可能。
所以,以后,当我们说到测试覆盖率为多少多少的时候,一定要有一个前提,你是用什么工具观察的。
分支覆盖率是一种比严格的观察工具,要达到分支覆盖率,需要付出巨大的努力。因此在具体项目中实施的时候,建议能够发现两种工具结合起来:将重点代码用分支覆盖率来要求,用不重点代码用代码覆盖率来要求。

sales@spasvo.com