软件测试作业

软件测试作业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: 循环条件没设置好,i > 0会导致循环无法进行到数组第一项,应该改成 i >= 0。
  • 数组x为空时,会抛出空指针错误,循环无法执行,也不会执行上面叙述的Fault。
  • 只要满足数组x[0]不是与y相等的唯一的元素即可避免Error,比如测试用例 x = [1, 2, 3, 4, 5, 6], y = 2, 这样得到返回结果 Expected = 1, 结果是正确的。
  • 当数组只有一个元素的时候,由于循环无法访问第一个元素(x[0]),所以循环无法进行,永远返回-1,导致Error。此时Failure产生未知, 如果这唯一的元素与y不相等,则Failure也不会产生。测试用例 x = [1], y = 2,此时   返回-1,只有Error,无Failure。

程序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
  • Fault: 循环错误,从前往后遍历,遇到第一个0便返回其下标,循环应改为for (int i=x.length-1; i >= 0; i--)。

  • 由于该程序从前往后遍历,循环至少执行一次,所以总会执行该Fault。

  • 循环如果无法执行便不会导致Error,即数组为空。另外若数组只有一个元素,这样不论如何遍历结果也相同,也不会引发Error。

  • 当数组有一个以上元素且只有一个元素为0时,此时循环返回的是第一个等于0的元素的下标,导致Error。但是由于只有一个元素等于0, 所以同时这也是最后一个等于0的元素的下标,则Failure不会产生。测试用例 x =

  • [1,0,1],Expected=1,此时只有Error,无Failure。

posted @ 2018-03-14 18:48  如果,当时  阅读(136)  评论(0编辑  收藏  举报