在學測試的時候,老師總是用JUnit作為示範,雖然平時也需要用java寫寫網頁,還是比較喜歡用c/c++來寫程式。所以找了個c++的單元測試架構——CppUnit。
CppUnit非常類似於Junit,因此上手起來還是比較方便的,不過裡面的一些宏還是有點難記。
首先先寫一個類,用來被測試:
| 代碼如下 |
複製代碼 |
//add.h
classAdd
{
public:
Add();
virtual~Add();
voidadd(inta);
voidset(int);
intgetResult();
private:
intnumber;
}; |
這個類先設定原始值的大小,然後可以調用add()函數增加number的大小,調用getRestlt()函數獲得number的當前值。
根據這個類寫一個測試類別:
| 代碼如下 |
複製代碼 |
//testadd.h
#include<cppunit/extensions/HelperMacros.h>
class TestAdd: public CppUnit::TestFixture
{
CPPUNIT_TEST_SUITE(TestAdd);
CPPUNIT_TEST(testAdd);
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void testAdd();
}; |
現通過宏CPPUNIT_TEST_SUITE添加測試類別,然後添加這個類中用於測試的函數,這裡只有一個函數是用來測試Add類的,就是testAdd()函數,所以使用CPPUNIT_TEST(testAdd);將這個函數設定為測試函數(類似於JUnit中的@Test註解)。如果需要添加其他函數也要在這裡增加,然後就是測試定義的結束CPPUNIT_TEST_SUITE_END();
這個類中可以有兩個函數,來設定運行測試前的環境和清理測試。這個和JUnit相似。
測試類別的實現:
| 代碼如下 |
複製代碼 |
#include"TestAdd.h"
#include"../src/Add.h"
CPPUNIT_TEST_SUITE_REGISTRATION(TestAdd);
voidTestAdd::setUp()
{
}
voidTestAdd::tearDown()
{
}
voidTestAdd::testAdd()
{
Addadd;
add.set(5);
add.add(10);
CPPUNIT_ASSERT_EQUAL(16, add.getResult());
} |
在實現檔案中的開始,需要使用CPPUNIT_TEST_SUITE_REGISTRATION來將這個類註冊到測試組件中,可以讓CppUnit自己尋找測試類別。
在測試函數testAdd中,使用了斷言 CPPUNIT_ASSERT_EQUAL來測試Add類操作後和預期值是否相等(這裡故意寫的不同)
| 代碼如下 |
複製代碼 |
main.cpp:
#include<cppunit/CompilerOutputter.h>
#include<cppunit/extensions/TestFactoryRegistry.h>
#include<cppunit/ui/text/TestRunner.h>
intmain(intargc, char* argv[])
{
// Get the top level suite from the registry
CppUnit::Test*suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunnerrunner;
runner.addTest( suite );
// Change the default outputter to a compiler error format outputter
runner.setOutputter( newCppUnit::CompilerOutputter( &runner.result(),
std::cerr ) );
// Run the tests.
boolwasSucessful = runner.run();
// Return error code 1 if the one of test failed.
returnwasSucessful ? 0 : 1;
} |
這裡的代碼直接從例子中抄來的,測試組件直接從TestFactoryRegistry裡面擷取,設定測試錯誤從標準錯誤流中輸出。
最後啟動並執行輸出:
| 代碼如下 |
複製代碼 |
.F
TestAdd.cpp:29:Assertion
Test name: TestAdd::testAdd
equality assertion failed
- Expected: 16
- Actual : 15
Failures !!!
Run: 1 Failure total: 1 Failures: 1 Errors: 0 |