您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > cppUnit
CppUnit快速使用指南
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時(shí)間:[ 2013/3/18 14:21:38 ] 推薦標(biāo)簽:

3. 手動(dòng)使用步驟

        首先要明確測試的對(duì)象 fixture,然后根據(jù)其功能、流程,以及以前的經(jīng)驗(yàn),確定測試用例。這個(gè)步驟非常重要,直接關(guān)系到測試的終效果。當(dāng)然增加測試用例的過程是個(gè)階段性的工作,開始完成代碼后,先完成對(duì)功能的測試用例,保證其完成功能;然后對(duì)可能出錯(cuò)的部分,結(jié)合以前的經(jīng)驗(yàn)(比如邊界值測試、路徑覆蓋測試等)編寫測試用例;后在發(fā)現(xiàn)相關(guān) bug 時(shí),根據(jù) bug 完成測試用例。

        比如對(duì)整數(shù)加法進(jìn)行測試,首先定義一個(gè)新的 TestFixture 子類,MathTest,編寫測試用例的測試代碼。后期需要添加新的測試用例時(shí)只需要添加新的測試函數(shù),根據(jù)需要修改 setUp 和 tearDown 即可。如果需要對(duì)新的 fixture 進(jìn)行測試,定義新的 TestFixture 子類即可。注:下面代碼僅用來表示原理,不能編譯。

/// MathTest.h
// A TestFixture subclass.
// Announce: use as your owner risk.
// Author  : liqun (liqun@nsfocus.com)
// Data    : 2003-7-5
#include "cppunit/TestFixture.h"
class MathTest : public CppUnit::TestFixture {
protected:
 int m_value1, m_value2;
 
public:
 MathTest() {}
 
 // 初始化函數(shù)
 void setUp ();
 // 清理函數(shù)
 void tearDown();
 
 // 測試加法的測試函數(shù)
 void testAdd ();
 // 可以添加新的測試函數(shù)
};
/// MathTest.cpp
// A TestFixture subclass.
// Announce: use as your owner risk.
// Author  : liqun (liqun@nsfocus.com)
// Data    : 2003-7-5
#include "MathTest.h"
#include "cppunit/TestAssert.h"
void MathTest::setUp()
{
     m_value1 = 2;
     m_value2 = 3;
}
void MathTest::tearDown()
{
}
void MathTest::testAdd()
{
     int result = m_value1 + m_value2;
     CPPUNIT_ASSERT( result == 5 );
}


        然后編寫 main 函數(shù),把需要測試的測試用例組織到 TestSuite 中,然后通過 TestRuner 運(yùn)行。這部分代碼后期添加新的測試用例時(shí)需要改動(dòng)的不多。只需要把新的測試用例添加到 TestSuite 中即可。

/// main.cpp
// Main file for cppunit test.
// Announce: use as your owner risk.
// Author  : liqun (liqun@nsfocus.com)
// Data    : 2003-7-5
// Note    : Cannot compile, only for study. 
#include "MathTest.h"
#include "cppunit/ui/text/TestRunner.h"
#include "cppunit/TestCaller.h"
#include "cppunit/TestSuite.h"
int main()
{
 CppUnit::TextUi::TestRunner runner;
 CppUnit::TestSuite *suite= new CppUnit::TestSuite();
 
 // 添加一個(gè)測試用例
 suite->addTest(new CppUnit::TestCaller<MathTest> (
               "testAdd", testAdd));
 
 // 指定運(yùn)行TestSuite
 runner.addTest( suite );
 // 開始運(yùn)行, 自動(dòng)顯示測試進(jìn)度和測試結(jié)果
 runner.run( "", true );    // Run all tests and wait
}

上一頁123下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請(qǐng)使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd