观察两段代码并回答下列问题:
(1)Identify the fault.
(2)If possible, identify a test case that does not execute the fault. (Reachability)
(3)If possible, identify a test case that executes the fault, but does not result in an error state.
(4)If possible identify a test case that results in an error, but not a failure.
代码一:
public int findLast (int[] x, int y) { //Effects: If x==null throw NullPointerException // else return the index of the last element // in x that equals y. // If no such element exists, return -1 for (int i=x.length-1; i > 0; i--) { if (x[i] == y) { return i; } } return -1; } // test: x=[2, 3, 5]; y = 2 // Expected = 0
fault: for循环的终止条件应为i>=0
不会执行fault的样例: x为null, y随意。由于x为null,for循环的变量i的赋值会因为null没有length所以抛出NullPointerException,不会到达fault的位置
Excepted: NullPointerException
Actual: NullPointerException
执行到fault但是并没有error的样例: x=[1,2,3,4,5] , y=2。 由于在i=1的时候就会因x[1]==y而终止循环,所以虽然每次for循环都会执行i>0的判断(执行fault),但是并没又因此而出现error(没有error是因为这个样例里并没有因为i>0这一fault而终止循环)。
Excepted: 1
Actual: 1
处于error但无failure的样例:x=[1,2,3,4,5] y=0。 由于y根本就不在x中,因此虽然程序跳出循环是因为fault(此时处于了error状态),但是结果仍是没找到,返回了-1.
Excepted: -1
Actual: -1
代码二:
public static int lastZero (int[] x) { //Effects: if x==null throw NullPointerException // else return the index of the LAST 0 in x. // Return -1 if 0 does not occur in x for (int i = 0; i < x.length; i++) { if (x[i] == 0) { return i; } } return -1; } // test: x=[0, 1, 0] // Expected = 2
fault: for循环的搜索顺序应该从大到小。即 for (int i=x.length-1; i>= 0; i--)
不会执行fault的样例: 不存在,所有的样例都会进入到for循环,一旦开始了i=0的赋值,就进入了fault
执行到fault但是并没有error的样例: x=[0] 。 由于数组的长度为1,所以这时就没有了从大到小或从小到大的概念了。fault不会引起error
Excepted: 0
Actual: 0
处于error但无failure的样例:x=[1,2,0,4,5] 。 由于检索的顺序反了,所以只要是数组内元素个数多于一个,就是处于error。
Excepted: 2
Actual: 2