Helper Macros
也許你已注意到,實作fixture的static函數suite()是重覆、容易出錯的細節。參考Writing test fixture這篇,創造一系列隱藏實作suite()細節的marco。
接著,用這些macro再重寫ComplexNumberTest的程式碼:
#include <cppunit/extensions/HelperMacros.h>
class ComplexNumberTest : public CppUnit::TestFixture {首先,我們先宣告CPPUNIT_TEST_SUITE(),把class name當參數丟進macro。
CPPUNIT_TEST_SUITE( ComplexNumberTest );省下在static suite()裡,建立CppUnit::TestSuite物件,建構子參數為class name這些細節。接著,用CPPUNIT_TEST()宣告fixture裡的每一個test case。
CPPUNIT_TEST( testEquality );
CPPUNIT_TEST( testAddition );最後,加上CPPUNIT_TEST_SUITE_END()結束整個宣告。
CPPUNIT_TEST_SUITE_END();重點來了!suite()函數的實作細節都省下來了。
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(CppUnit::TestSuite)的TestCaller,它用的類別,就是fixture的類別名稱,以及在該類別裡的函數名稱。在這裡,指的是ComplexNumberTest::testEquality和ComplexNumberTest::testAddition。
helper macro已經幫你寫好一些常用的assertion。例如確認ComplexNumber在除以0時會throw出MathException。
在使用marco的suite段落中,加上CPPUNIT_TEST_EXCEPTION(),並且將test case函數名稱與預期會throw出來的exception型別當作參數丟進去。
撰寫test case函數
CPPUNIT_TEST_SUITE( ComplexNumberTest );
//...
CPPUNIT_TEST_EXCEPTION( testDivideByZeroThrows, MathException );
CPPUNIT_TEST_SUITE_END();
//...
void testDivideByZeroThrows()
{
*m_10_1 / ComplexNumber(0); // The following line should throw a MathException.
}如果預期的exception沒有throw出來,報告中會記錄asserttion failure,測試不通過。
譯註
原文: automatically implements the static suite() method. 翻譯成:「可以隱藏static函數
suite()的實作細節」意同「自動化實作....這個函數」好怪!所以這樣翻。原文: "ComplexNumberTest.testEquality" and "ComplexNumberTest.testAddition"。 翻譯成:
ComplexNumberTest::testEquality和ComplexNumberTest::testAddition。 在C++中,通常會用::接函數名稱,表示「類別裡的函數」;用.接函數名稱,表示「 物件裡的函數」comon應該是common的筆誤。
Last updated
Was this helpful?