1.CppUnit使用
函數 | 使用 |
---|---|
Fixture | 一個或一組測試用例的測試對象。可以是你要測試的對象或者函數。 |
TestCase | 測試用例。是對測試對象的某個功能或流程編寫的測試代碼。對一個Fixture,可能有多個測試用例。 |
TestSuite | 同時運行的測試用例的集合。可以是一個fixture的多個測試函數、也可以是多個fixture的所有測試用例。 |
使用時,在測試的主文件中將TestCase註冊到TestSuite中,並運行。 |
流程圖:
2.CppUnit實例
新建MathTest頭文件.h
class MathTest : public CppUnit::TestFixture {
// 添加一個TestSuite
CPPUNIT_TEST_SUITE( MathTest );
// 添加測試用例到TestSuite, 定義新的測試用例需要在這兒聲明一下
CPPUNIT_TEST( testAdd );
CPPUNIT_TEST( testSub );
CPPUNIT_TEST_SUITE_END();
protected:
int x, y;
public:
MathTest() {}
// 初始化函數
void setUp ();
// 清理函數
void tearDown();
// 測試加法的測試函數
void testAdd ();
// 測試減法的測試函數
void testSub ();
};
#endif //WW_TEST_MATHTEST_H
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
新建MathTest實現類.cpp
//將TestSuite註冊到一個名爲alltest的TestSuite中
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(MathTest,"alltest");
void MathTest::setUp()
{
x = 2;
y = 3;
}
void MathTest::tearDown()
{
}
void MathTest::testAdd()
{
int result = x + y;
CPPUNIT_ASSERT( result == 5 );
}
void MathTest::testSub()
{
int result = x + y;
CPPUNIT_ASSERT( result == 1 );
}
#include "MathTest.h"
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
main類
int main()
{
CppUnit::TextUi::TestRunner runner;
// 從註冊的TestSuite中獲取特定的TestSuite, 沒有參數獲取未命名的TestSuite.
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry("alltest");
// 添加這個TestSuite到TestRunner中
runner.addTest( registry.makeTest() );
// 運行測試
runner.run();
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
3.編譯程序
輸入一下命令,進行編譯
g++ -L /usr/local/lib/libcppunit.a main.cpp MathTest.cpp -lcppunit -ldl -o MathTest
- 1
/usr/local/lib/libcppunit.a爲安裝CppUnit是的libcppunit.a路徑
main.cpp 、MathTest.cpp爲要編譯的cpp文件
MathTest爲編譯生成的可執行文件
運行:./MathTest
運行結果如下
查看編譯完成後,MathTest具體實現
-E MathTest.cpp -o MathTest.E
- 1
使用gedit打開MathTest.E文件
./MathTest.E&
- 1