TestFactoryRegistry解決兩個常犯的失誤:
忘記在fixture寫好的static函數suite()加到主程式的test runner(因為它需要另外加在主程式上,很容易漏掉)。
在主程式上忘記include所有fixture的.h檔 (可以看previous example
)
在TestFactoryRegistry初始化時,會註冊即將執行的suite()。
註冊ComplexNumber的suite(),需在它的.cpp檔加上下列程式碼:
Copy //ComplexNumber.cpp
#include <cppunit/extensions/HelperMacros.h>
CPPUNIT_TEST_SUITE_REGISTRATION( ComplexNumber );
裡面實作的細節如下,先宣告static的AutoRegisterSuite
變數。建構時,生成一個TestSuiteFactory
,再將它註冊到TestFactoryRegistry
裡。TestSuiteFactory
回傳的是fixture::suite()的回傳值(TestSuite*
)。
執行測試,用下列程式碼執行test runner,我們不必在主程式上面include任何fixture的.h檔。:
Copy #include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
int main( int argc, char **argv)
{
CppUnit::TextUi::TestRunner runner;
首先,我們取得TestFactoryRegistry
的參考:
Copy CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry();
TestFactoryRegistry::makeTest()會new出所有用CPPUNIT_TEST_SUITE_REGISTRATION()
註冊的TestSuite
,我們把它加到`test runner。
Copy runner.addTest( registry.makeTest() );
runner.run();
return 0;
}
譯註
原文: compilation bottleneck caused by the inclusion of all test case headers
譯文1: include了所有fixture的.h檔造成的compilation bottleneck(編譯瓶頸)
譯文2: 在主程式上忘記加上所有fixture的.h檔
原文: since it is in another file, it is easy to forget
譯文: 因為它需要另外加在主程式上,很容易漏掉
原文: retreive the instance of the TestFactoryRegistry
譯文: 取得TestFactoryRegistry
的參考(從程式碼看起來是這樣呀)
CPPUNIT_TEST_SUITE_REGISTRATION()
實作細節,建構AutoRegisterSuite
的source code內容:
Copy //AutoRegisterSuite.h
TestFactoryRegistry* m_registry;
TestSuiteFactory<TestCaseType> m_factory;
AutoRegisterSuite()
: m_registry( &TestFactoryRegistry::getRegistry() )
{
m_registry->registerFactory( &m_factory );
}
AutoRegisterSuite( const std::string &name )
: m_registry( &TestFactoryRegistry::getRegistry( name ) )
{
m_registry->registerFactory( &m_factory );
}
Copy //TestFactoryRegistry.cpp
Test* TestFactoryRegistry::makeTest()
{
TestSuite *suite = new TestSuite( m_name );
addTestToSuite( suite );
return suite;
}
void TestFactoryRegistry::addTestToSuite( TestSuite *suite )
{
for ( Factories::iterator it = m_factories.begin();
it != m_factories.end();
++it )
{
TestFactory *factory = *it;
suite->addTest( factory->makeTest() );
}
}