库安装
下载cppunit-1.12.0.tar.gz
标准的解压加安装:
$ tar xzvf cppunit-1.12.0.tar.gz
$ cd cppunit-1.12.0
$ ./configure
$ make
$ make install
配置共享库
$ vi /etc/ld.so.conf //在文件中添加 /usr/local/lib
$ ldconfig -v | grep cppunit //查看是否配置好了cppunit的共享库
基本原理
测试对象被称为 Fixture,对 fixture 的所有测试用例应封装在 CppUnit::TestFixture 的派生类。要把对 fixture 的一个测试函数转变成一个测试用例,需要生成一个 CppUnit::TestCaller 对象。而最终运行整个应用程序的测试代码的时候,可能需要同时运行对一个 fixture 的多个测试函数,甚至多个 fixture 的测试用例。CppUnit 中把这种同时运行的测试案例的集合称为 TestSuite。而 TestRunner 则运行测试用例或者 TestSuite。
测试宏
CPPUNIT_ASSERT(condition);// 确信condition为真
CPPUNIT_ASSERT_MESSAGE(message, condition);// 当condition为假时失败, 并打印message
CPPUNIT_FAIL(message);// 当前测试失败, 并打印message
CPPUNIT_ASSERT_EQUAL(expected, actual);// 确信两者相等
CPPUNIT_ASSERT_EQUAL_MESSAGE(message, expected, actual);// 失败的同时打印message
CPPUNIT_ASSERT_DOUBLES_EQUAL(expected, actual, delta);// 当expected和actual之间
范例
//main.h //初始化testsuit和testrunner。此代码不常改动
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
using namespace CppUnit;
int main()
{
CPPUNIT_NS::TestResult controller; // Create the event manager and test controller
CPPUNIT_NS::TestResultCollector result; // Add a listener that colllects test result
controller.addListener( &result );
CPPUNIT_NS::BriefTestProgressListener progress;// Add a listener that print dots as test run.
controller.addListener( &progress );
CPPUNIT_NS::TestRunner runner; // Add the top suite to the test runner
runner.addTest( CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest() );
runner.run( controller );
CPPUNIT_NS::CompilerOutputter outputter( &result, CPPUNIT_NS::stdCOut() ); // Print test in a compiler compatible format.
outputter.write();
return result.wasSuccessful() ? 0 : 1; 31
}
//MathTest.h //测试类定义
#include"cppunit/TestFixture.h"
#include "cppunit/extensions/HelperMacros.h"
using namespace CppUnit;
class MathTest: public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(MathTest);
CPPUNIT_TEST(TAdd); //加测试方法
CPPUNIT_TEST_SUITE_END();
public:
MathTest() {}
~MathTest() {}
void setUp();
void tearDown();
void TAdd();
};
//注册用例
CPPUNIT_TEST_SUITE_REGISTRATION(MathTest);
//MathTest.cpp //测试类实现
#include"mathTest.h"
#include"cppunit/TestAssert.h"
void MathTest::setUp()
{
}
void MathTest::tearDown()
{
}
void MathTest::TAdd()
{
CPPUNIT_ASSERT(10 == 5+5);
}
//makefile
demo:main.o mathTest.o
g++ -o demo -ldl -lcppunit main.o mathTest.o //-ldl共享库
main.o:main.cpp
g++ -c main.cpp
mathTest.o:mathTest.h mathTest.cpp
g++ -c mathTest.cpp
clean:
rm demo main.o mathTest.o
#!/bin/bash
#run.sh 循环编译和执行的shell脚本
while ( true )
do
make
./demo
sleep 3
done
$sh run.sh