四、下面是完整的程序清单
// 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();
//写一个注册函数, 使其在运行期生成一个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); //执行Add操作
CPPUNIT_ASSERT_EQUAL(30, nResult); //检查结果是否等于30
}
std::string CPlusTestCase::GetSuiteName()
{
return "CPlus";
}
/*
* 注意:CPlusTestCase::GetSuite()返回一个指向CppUnit::Test的指针.
* 这个指针是整个测试的起点。
* CppUnit::TestFactoryRegistry::getRegistry()根据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;
}