CppUnit -- 作为C++语言的一款测试工具,其实也是一个开源项目,与JUnit一样,用来方便开发人员进行单元测试的工具。
项目地址:http://sourceforge.net/apps/mediawiki/cppunit/index.php?title=Main_Page
1. 安装
在linux下很容易,只要在软件管理中心搜索即可,然后在Eclipse CDT中新建项目,将cppunit加入项目的link library
2. 简单例子:测试一个计算器类,有加减乘除运算
#include <iostream>
//引入CppUnit相关头文件
#include "cppunit/TestCase.h"
#include "cppunit/TestResult.h"
#include "cppunit/TestResultCollector.h"
#include "cppunit/TestCaller.h"
#include "cppunit/TextOutputter.h"
using namespace std;
//被测试类,简单计算器
class SimpleCalculator {
public:
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
};
//测试类,继承TestCase类
class SimpleCalculatorTest : public CPPUNIT_NS::TestCase {
public:
//测试开始前初始化
virtual void setUp() {
pSc = new SimpleCalculator();
}
//测试结束后资源清理
virtual void tearDown() {
delete pSc;
}
//测试方法
void testAdd() {
CPPUNIT_ASSERT_EQUAL(pSc->add(5,6), 11);
}
void testDiv() {
CPPUNIT_ASSERT_EQUAL(pSc->div(10,1), 0);
}
private:
SimpleCalculator *pSc;
};
int main() {
CPPUNIT_NS::TestResult tr;
CPPUNIT_NS::TestResultCollector resultCollector;
tr.addListener(&resultCollector);
//testAdd
CPPUNIT_NS::TestCaller<SimpleCalculatorTest> tcAdd("testAdd", &SimpleCalculatorTest::testAdd);
tcAdd.run(&tr);
//testDiv
CPPUNIT_NS::TestCaller<SimpleCalculatorTest> tcDiv("testDiv", &SimpleCalculatorTest::testDiv);
tcDiv.run(&tr);
CPPUNIT_NS::TextOutputter output(&resultCollector, std::cout);
output.write();
return 0;
}
/*
CPPUNIT_ASSERT_EQUAL(pSc->div(1,10), 0);
OK (2 tests)
CPPUNIT_ASSERT_EQUAL(pSc->div(10,1), 0);
!!!FAILURES!!!
Test Results:
Run: 2 Failures: 1 Errors: 0
1) test: testDiv (F) line: 54 ../src/TestCppUnit3.cpp
equality assertion failed
- Expected: 10
- Actual : 0
*/