C++编程思想 第2卷 第2章 防御性编程 一个简单的单元测试框架 TestSuite框架

本文介绍了C++编程中的防御性编程概念,重点讲解了一个名为TestSuite的单元测试框架。该框架包括Test和Suite两个核心类,Test类作为抽象基类用于记录测试结果,Suite则用于组织测试。通过实例化测试对象如DateTest并调用run()函数,可以轻松运行测试案例。Test类利用RTTI获取测试类名,并在报告中展示。当测试失败时,test_()宏能提供详细的失败信息,包括文件名和行号。此外,框架还提供了succeed_()和fail_()函数来处理异常情况。
摘要由CSDN通过智能技术生成

测试套件框架 TestSuite Framework,TestSuite包含两个主要的类:Test
和Suite

Test类是一个抽象基类,可以从这个类派生用户自己的测试对象
Test类保存着测试时成功和失败的次数,测试失败时能够显示相关测试条件
等信息使用框架来测试Date类

//: C02:DateTest.h
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
#ifndef DATETEST_H
#define DATETEST_H
#include "Date.h"
#include "../TestSuite/Test.h"

class DateTest : public TestSuite::Test {
  Date mybday;
  Date today;
  Date myevebday;
public:
  DateTest(): mybday(1951, 10, 1), myevebday("19510930") {}
  void run() {
    testOps();
    testFunctions();
    testDuration();
  }
  void testOps() {
    test_(mybday < today);
    test_(mybday <= today);
    test_(mybday != today);
    test_(mybday == mybday);
    test_(mybday >= mybday);
    test_(mybday <= mybday);
    test_(myevebday < mybday);
    test_(mybday > myevebday);
    test_(mybday >= myevebday);
    test_(mybday != myevebday);
  }
  void testFunctions() {
    test_(mybday.getYear() == 1951);
    test_(mybday.getMonth() == 10);
    test_(mybday.getDay() == 1);
    test_(myevebday.getYear() == 1951);
    test_(myevebday.getMonth() == 9);
    test_(myevebday.getDay() == 30);
    test_(mybday.toString() == "19511001");
    test_(myevebday.toString() == "19510930");
  }
  void testDuration() {
    Date d2(2003, 7, 4);
    Date::Duration dur = duration(mybday, d2);
    test_(dur.years == 51);
    test_(dur.months == 9);
    test_(dur.days == 3);
  }
};
#endif // DATETEST_H ///:~

运行测试案例简单,只需实例化一个DateTest对象并调用它的成员函数run()就可以了

//: C02:DateTest.cpp
// From "Thinking in C++, Volume 2", by Bruce Eckel & Chuck Allison.
// (c) 1995-2004 MindView, Inc. All Rights Reserved.
// See source code use permissions stated in the file 'License.txt',
// distributed with the code package available at www.MindView.net.
// Automated testing (with a framework).
//{L} Date ../TestSuite/Test
#include <iostream>
#include "DateTest.h"
using namespace std;

int main() {
  DateTest test;
  test.run();
  return test.report();
  getchar();
}
/* Output:
Test "DateTest":
        Passed: 21,      Failed: 0
*/ ///:~

Test::report()函数显示前面的输出,并且把测试失败的次数作为返回值,
这个

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值