HW2——Failure, Error, Fault
Homework 2
Below are two faulty programs. Each includes a test case that results in failure. Answer the following questions (in the next slide) about each program.
public intfindLast(int[] x, inty) {
//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
1.Identify the fault.
i> 0 ,i>0会忽略数组中的第一个值,故应改为i>=0.
2.If possible, identify a test case that does not execute the fault. (Reachability)
x=[] y=4 expected=-1 actual=-1
x=[1,2,3] y=4 expected=-1 actual=-1
x=[1,2,3] y=2 expected=1 actual=1
3.if possible, identify a test case that executes the fault, but not result in an error state
x = [2, 3, 2, 6], y=2
4.If possible identify a test case that results in an error, but not a failure.
x=[1] y=4 expected=-1 actual=-1
public static intlastZero(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.
应该从后遍历,for (int i=x.length-1; i >= 0; i--)
2.If possible, identify a test case that does not execute the fault. (Reachability)
程序总会执行int i=0 故肯定会执行Fault,即使x=null也会执行Fault。
3.if possible, identify a test case that executes the fault, but not result in an error state
x=null
4.If possible identify a test case that results in an error, but not a failure.
x=[1, 0, 2]