TestFactoryRegistry

TestFactoryRegistry解決兩個常犯的失誤:

  • 忘記在fixture寫好的static函數suite()加到主程式的test runner(因為它需要另外加在主程式上,很容易漏掉)。

  • 在主程式上忘記include所有fixture的.h檔 (可以看previous example)

在TestFactoryRegistry初始化時,會註冊即將執行的suite()。

註冊ComplexNumber的suite(),需在它的.cpp檔加上下列程式碼:

//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檔。:

#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

int main( int argc, char **argv)
{
  CppUnit::TextUi::TestRunner runner;

首先,我們取得TestFactoryRegistry的參考:

  CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry();

TestFactoryRegistry::makeTest()會new出所有用CPPUNIT_TEST_SUITE_REGISTRATION()註冊的TestSuite,我們把它加到`test runner。

  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是retrieve的筆誤

  • 原文: retreive the instance of the TestFactoryRegistry 譯文: 取得TestFactoryRegistry的參考(從程式碼看起來是這樣呀)

  • CPPUNIT_TEST_SUITE_REGISTRATION()實作細節,建構AutoRegisterSuite的source code內容:

//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 );
  }
  • makeTest()實作細節

//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() );
  }
}

Last updated