单元测试:查找list[]中的最大值

 原始代码如下:
int Largest(int list[], int length)
{
     int i,max;
     for(i = 0; i < (length – 1); i ++ )
     {
          if(list[i] > max) 
          {
                max=list[i];
          }
      }
      return max;
}

 

比如int a[]={7,8,9},b[]={-3,-1,-5},c[3],d[4]={7,8,7,8},e[]={0}........

这些例子有特殊性,在编写测试单元时,要选取边界值,特殊值。比如数组里都是整数,都是负数,有正有负,空,只有一个元素,存在重复的最大值.......


 对源程序的修改:

首先max未初始化:用list[0]来作为max的初始值;

然后发现for循环结束条件有错:将for循环中i < length-1修改成为i < length

异常处理,将抛出一个异常

编译源文件并运行该测试:增加提示信息;

if(list==NULL||length==0)
 {
  cout<<"error!input null!";      //输出提示信息
  return 0;                             //返回特殊值
 }

 修改后的测试程序:

#include<iostream>
#define null -858993460
using namespace std;

void main()
{
    int largest(int list[],int length);

    int a[]={7,8,9},b[]={-3,-1,-5},c[3],d[4]={7,8,7,8},e[]={0},max;
    
    max=largest(a,3);
    cout<<max<<endl;
    max=largest(b,3);
    cout<<max<<endl;
    max=largest(c,0);
    cout<<max<<endl;
    max=largest(d,4);
    cout<<max<<endl;
    max=largest(e,1);
    cout<<max<<endl;
}

int largest(int list[],int length)
{
    int i,max=list[0];
    if(list==NULL||length==0)
    {
        cout<<"error!input null!";      //输出提示信息
        return 0;                       //返回特殊值
    }

    for(i=1;i<(length);i++)
    {
        if(list[i]>max)
        {
            max=list[i];
        }
    }
    return max;

}

总结:

单元测试可以使代码规范,代码有效性,健壮性体现出来。面对程序整合时的种种不可预知问题,优化过的代码更加有效,BUG也更少,在软件开发中,单元测试必不可少。

原文地址:https://www.cnblogs.com/zhaotian/p/3590893.html