2-2 一个简单的单元测试框架

2.2 一个简单的单元测试框架

2.2.1 自动测试

下面是一个日期类:

#ifnef DATE1_H
#define DATE1_H
#include <string>
class Date{
public:
struct Duration{
int years;
int months;
int days;
Duration(int y, int m, int d)
: year(y), months(m), days(d) {}
};
Date();
Date(int year, int month, int day);
Date(const std::string&);
int getYear() const;
int getMonth() const;
int getDay() const;
std::string toString() const;
friend bool operator<(const Date&, const Date&);
friend bool operator>(const Date&, const Date&);
friend bool operator<=(const Date&, const Date&);
friend bool operator>=(const Date&, const Date&);
friend bool operator==(const Date&, const Date&);
friend bool operator!=(const Date&, const Date&);
friend Duration duration(const Date&, const Date&);
}
#endif

下面是一个有关的单元测试:

#include <iostream>
#include "Date.h"
using namespace std;

int nPass = 0, nFail = 0;
void test(bool t) { if(t) nPass++; else nFail++; }

int main()
{
Date mybday(1951, 10, 1);
test(mybday.getYear()==1951);
test(mybday.getMonth()==10);
test(mybday.getDay()==1);
cout<<"Passed:"<<nPass<<", Failed:"
<<nFail<<endl;
}

2.2.2 单元测试的评判标准

  • 代码覆盖率:一定要保证覆盖到每一行代码,即被调用的程序的每一行代码都被执行

  • 组合测试:对同样的结果进行不同组合函数达到相同效果的测试。

2.2.3 常用的测试框架

1. 小型项目:
  • TestSuite

  • UnitTest++

2.轻量级框架
  • Catch2

  • doctest

3.功能强大,使用广泛
  • Google Test