2、含宏的文本方式测试
  要方便添加测试代码,利用CppUnit提供的几个宏来进行:

 

//声明一个TestSuite
CPPUNIT_TEST_SUITE(MathTest);
//添加测试用例到TestSuite,定义新的测试用例需要在这里声明一下
CPPUNIT_TEST(testAdd);
//TestSuite声明完成
CPPUNIT_TEST_SUITE_END();
示例程序如下:
Main.cpp
#include<iostream>
using namespace std;
#include "cppunit/extensions/TestFactoryRegistry.h"
#include "cppunit/ui/text/TestRunner.h"
#pragma comment (lib, "cppunitd_dll.lib")
//如果不更改TestSuite,则本文件后期不需要更改
int main()
{
CppUnit::TextUi::TestRunnerrunner;
//从注册的TestSuite中获取待定的TestSuite,没有参数获取未命名的TestSuite
CppUnit::TestFactoryRegistry&registry = CppUnit::TestFactoryRegistry::getRegistry("alltest");
//添加这个TestSuite到TestRunner
runner.addTest(registry.makeTest());
//允许测试
runner.run();
return 0;
}
MathTest.h
/*使用宏的CPPUNIT*/
#include "cppunit/extensions/HelperMacros.h"
class MathTest:public CppUnit::TestFixture
{
//声明一个TestSuite
CPPUNIT_TEST_SUITE(MathTest);
//添加测试用例到TestSuite,定义新的测试用例需要在这里声明一下
CPPUNIT_TEST(testAdd);
//TestSuite声明完成
CPPUNIT_TEST_SUITE_END();
public:
//初始化函数
void setUp();
//清理函数
voidtearDown();
//测试加法的测试函数
void testAdd();
protected:
intm_value1,m_value2;
};
MathTest.cpp
#define MATHTEST_H
#ifdef MATHTEST_H
#include "MathTest.h"
#include "cppunit/TestAssert.h"
#endif
//把这个TestSuite注册到名为"alltest"的TestSuite中,如果未定义,则会自动定义
//也可以CPPUNIT_TEST_SUITE_REGISTRATION(MathTest);注册到全局的一个未命名的TestSuite中
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MathTest,"alltest");
void MathTest::setUp()
{
m_value1 = 2;
m_value2 = 3;
}
void MathTest::tearDown()
{
}
void MathTest::testAdd()
{
int ret =m_value1 + m_value2;
CPPUNIT_ASSERT(ret== 5);
}