Sur*_*tta 6 java junit testcase
问题陈述是
一个零故障的方法,您可以编写一个测试套件,它具有100%的语句覆盖率,但没有找到故障,另一个具有100%分支覆盖率的测试套件确实显示了故障?
这是我为此写的方法
public faultyMethod1(int x, int y) {
int X =x;
int Y = y;
if (Y !=0){
Z = X/Y;
} else {
System.out.println("Sorry. That's an DiviDeByZeroException");
}
}
faultyMethod1 (1,2);
faultyMethod1 (2,0);
Run Code Online (Sandbox Code Playgroud)
上面的代码实现了具有100%分支覆盖率的测试套件,确实揭示了故障"
怎么样测试套件到具有100%的语句覆盖,但是没有找到故障?
让我们再举一个例子......
// The method, according to our imaginary specification, should do:
// return x * y, IF x is less than 2
// return x + y, in any other case
public int doSomething(int x, int y) {
if (x < 2 ) {
return x * x; // this is our bug, it SHOULD be x * y
}
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
现在想象我们有两个测试:
assertEquals(0, doSomething( 0, 12) ); // works, as 0 * 0 == 0 * 12
assertEquals(20, doSomething( 10, 10 ) ); // works fine
Run Code Online (Sandbox Code Playgroud)
所以,现在我们有100%的测试覆盖率(因为x <2分支已被覆盖,而另一个分支覆盖).但是我们没有找到错误,因为使用零作为x的值隐藏它(因为0*某事总是0,y是无关紧要的).我们需要这样的东西......
assertEquals(12, doSomething( 1, 12) ); // fails, because it will be 1*1 == 1
Run Code Online (Sandbox Code Playgroud)
任何其他情况都可能出现同样的问题,包括除以零.无法想象一个很好的例子,但我想你得到的基本想法是如何100%覆盖并不意味着找到100%的所有错误.(找到它们的一种很酷的方法是进行突变测试,但这是一个非常高级的主题.)
| 归档时间: |
|
| 查看次数: |
2895 次 |
| 最近记录: |