软件测试 Homework2
Below are four faulty programs. Each includes a test case that results in
failure. Answer the following questions (in the next slide) about each program.
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
2.
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
(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.
1.
(1) 代码中i > 0 应为 i >= 0
(2) x = NULL y = 1 expect: NullPointerException result: NullPointerException 未执行错误代码
(3) x = [3, 4, 5] y = 5 expect: 2 result: 2 通过且执行了错误相关代码未产生error
(4) x = [3, 4, 5] y = 2 expect: -1 result: -1 通过,但是在i=0时就跳出了循环(error)
2.
(1) 代码中 int i = 0; i < x.length; i++ 应为 int i = x.length - 1; i >= 0; i--
(2) x = NULL expect: NullPointerException result: NullPointerException 未执行错误代码
(3) 不存在这种情况。只要执行到了错误代码,i就从0开始迭代不断变大,即产生了error
(4) x = [2, 0, 1] expect: 1 result: 1 循环从i=0开始变大(error)