您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > cppUnit
CppUnit Cookbook中文版
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2014/1/2 10:04:17 ] 推薦標簽:CppUnit 單元測試

下面是使用這些宏重寫了類ComplexNumberTest后的代碼:
#include <cppunit/extensions/HelperMacros.h>

class ComplexNumberTest : public CppUnit::TestFixture {

首先我們聲明這個suite,把這個類的名字傳遞給宏:
CPPUNIT_TEST_SUITE( ComplexNumberTest );

這個使用靜態(tài)的suite() method建立的suite以類的名字來命名。然后,我們?yōu)槊總測試用例聲明:
CPPUNIT_TEST( testEquality );
CPPUNIT_TEST( testAddition );

后,我們結(jié)束這個suite聲明:
CPPUNIT_TEST_SUITE_END();

在這里下面這個method已經(jīng)被實現(xiàn)了:
static CppUnit::TestSuite *suite();

剩下的fixture保持不動:
private:
Complex *m_10_1, *m_1_1, *m_11_2;
protected:
void setUp()
{
m_10_1 = new Complex( 10, 1 );
m_1_1 = new Complex( 1, 1 );
m_11_2 = new Complex( 11, 2 );
}

void tearDown()
{
delete m_10_1;
delete m_1_1;
delete m_11_2;
}

void testEquality()
{
CPPUNIT_ASSERT( *m_10_1 == *m_10_1 );
CPPUNIT_ASSERT( !(*m_10_1 == *m_11_2) );
}

void testAddition()
{
CPPUNIT_ASSERT( *m_10_1 + *m_1_1 == *m_11_2 );
}
};

加入這個suite的TestCaller的名字是這個fixture名字和method名字的組合。
對目前這個用例來說,名字會是"ComplexNumberTest.testEquality" 和"ComplexNumberTest.testAddition".

helper macros幫你寫些常用的斷言。例如。檢查當(dāng)一個數(shù)被零除的時候ComplexNumber是否會拋出MathException異常:
*把這個測試用例加入使用CPPUNIT_TEST_EXCEPTION的suite中,指定希望的異常的類型。
*寫這個測試用例的method

CPPUNIT_TEST_SUITE( ComplexNumberTest );
// [...]
CPPUNIT_TEST_EXCEPTION( testDivideByZeroThrows, MathException );
CPPUNIT_TEST_SUITE_END();

// [...]

void testDivideByZeroThrows()
{
// The following line should throw a MathException.
*m_10_1 / ComplexNumber(0);
}

如果期望的異常沒有被拋出,這個斷言會失敗。

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