软件测试-HW2

作业要求

观察两段代码并回答下列问题:

(1)Identify the fault.(找到错误代码)
(2)If possible, identify a test case that does not execute the fault. (Reachability)(试着编写测试用例,不执行fault部分)
(3)If possible, identify a test case that executes the fault, but does not result in an error state.(执行fault部分,但不出现error情况)
(4)If possible identify a test case that results in an error, but not a failure.(出现error情况,但不发生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

解答:
(1)错误代码:for循环的终止条件应该为i <= 0;
(2)测试用例:x = [], y = 2;
这里由于x为空,所以不进入for循环,直接返回NullPointerException;
Excepted:NullPointerException,
Actual:NullPointerException;
(3)测试用例:x = [1, 2, 3], y = 2;
这里最后一个等于y的值不在x[0]处,而在x[1],所以for循环并没有执行到"i >= 0"的条件出,所以不会出现error状态;
Excepted:1
Actual:1
(4)测试用例:x = [3, 4, 5], y = 2;
这里虽然执行到了error状况,但由于x中并没有与y相等的值,所以得到结果是正确的,所以没有出现failure;
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

解答:
(1)错误代码:for循环执行的方向反了,不应该由i = 0开始执行,而应该是从x.length - 1开始递减;
(2)这里无论如何代码都会执行进入for循环,所以不存在这样的样例;
(3)测试用例:x = [1];
这里执行时会进入for循环,即进入了fault,但是由于x中只有一个元素,所以不存在循环执行的正反问题,所以没有error状态;
Excepted:-1
Actual:-1
(4)测试用例:x = [1, 0, 2];
这里代码执行时会发生error状态,但是由于x中只有一个0,所以无论是正着执行for循环还是倒着执行,都不会对结果产生影响,所以没有发生failure;
Excepted:1
Actual:1

posted @ 2017-03-02 23:03  阳光不搭  阅读(162)  评论(0编辑  收藏  举报