四、下面是完整的程序清單
// PlusTestCase.h
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <string>
#include <cppunit/TestCase.h>
#include <CppUnit/extensions/HelperMacros.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestAssert.h>
class CPlusTestCase : public CppUnit::TestCase
{
//通過這幾個宏,我們把CPlusTestCase和testAdd注冊到了測試列表當中.
CPPUNIT_TEST_SUITE(CPlusTestCase); //聲明一個測試包
CPPUNIT_TEST(testAdd); //聲明一個測試用例
CPPUNIT_TEST_SUITE_END();
public:
CPlusTestCase();
virtual ~CPlusTestCase();
void testAdd(); //測試方法
static std::string GetSuiteName();
//寫一個注冊函數(shù), 使其在運行期生成一個Test
static CppUnit::Test* GetSuite();
};
// PlusTestCase.cpp
#include "stdafx.h"
#include "UnitTest.h"
#include "PlusTestCase.h"
#include "plus.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
//注冊一個測試suite到一個指定的TestFactory工廠中
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(CPlusTestCase, CPlusTestCase::GetSuiteName());
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CPlusTestCase::CPlusTestCase()
{
}
CPlusTestCase::~CPlusTestCase()
{
}
void CPlusTestCase::testAdd()
{
CPlus plus;
int nResult = plus.Add(10, 20); //執(zhí)行Add操作
CPPUNIT_ASSERT_EQUAL(30, nResult); //檢查結果是否等于30
}
std::string CPlusTestCase::GetSuiteName()
{
return "CPlus";
}
/*
* 注意:CPlusTestCase::GetSuite()返回一個指向CppUnit::Test的指針.
* 這個指針是整個測試的起點。
* CppUnit::TestFactoryRegistry::getRegistry()根據(jù)TestSuite的名字返回TestFactoryRegistry工
* 然后調用工廠里的makeTest()對TestSuite進行組裝,將建立起一個樹狀的測試結構。
*/
CppUnit::Test* CPlusTestCase::GetSuite()
{
CppUnit::TestFactoryRegistry& reg = CppUnit::TestFactoryRegistry::getRegistry(CPlusTestCase::GetSuiteName());
return reg.makeTest();
}
// UnitTest.cpp
#include "stdafx.h"
#include "UnitTest.h"
#include <cppunit/ui/mfc/TestRunner.h>
#include "PlusTestCase.h"
…
/////////////////////////////////////////////////////////////////////////////
// CUnitTestApp initialization
BOOL CUnitTestApp::InitInstance()
{
…
CppUnit::MfcUi::TestRunner runner;
runner.addTest(CPlusTestCase::GetSuite()); //添加測試 runner.addTest(CMinusTestCase::GetSuite());
runner.run(); //show UI
/* CUnitTestDlg dlg;
m_pMainWnd = &dlg;
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
*/
return FALSE;
}