软件测试作业2
1.找出程序中的错误:
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:因为数组是从0开始的,所以循环的时候应该从数组长度减一一直到零
修正:for (int i=x.length-1; i > 0; i--)应改为for (int i=x.length-1; i >= 0; i--)
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 (int i = 0; i < x.length; i++)改为for (int i = x.length-1; i >=0; i--)
2.If possible, identify a test case that does not execute the fault. (Reachability)
代码一:test: x=[]; y = 6
代码二:test: x=[];
都是空不执行直接抛出异常
3.If possible, identify a test case that executes the fault, but does not result in an error state.
代码一:test: x=[2, 3, 5]; y = 5 结果为2,正确,因为没有到x[0]就返回了,不算error
代码二:test: x=[0,2,3]; 结果为0,因为只有一个0
4.If possible identify a test case that results in an error, but not a failure.
代码一:test: x=[0, 3, 5]; y = 6 结果为-1,正确
代码二:test: x=[2, 3, 0]; 结果为2,正确