1. 创建基于对话框的MFC项目:
其他步骤,默认即可。
2. 将cppunit所用的包拷入项目当前目录下。
3. 添加cppunit目录为系统目录:
4. 添加项目所依赖的lib库
有:testrunner.lib 与 cppunitd.lib
5. 准备好所要测试的类。
6. 编写测试用例:
1) 编写测试用例注册类,如:PlusTestSuite
需引入:<cppunit/TestSuite.h>
<cppunit/extensions/TestFactoryRegistry.h>
并添加两个方法: static CppUnit::Test *suite();
static std::string plusSuiteName();
.h文件源代码:
// PlusTestUnit.h: interface for the CPlusTestUnit class.
//
//
#if !defined(AFX_PLUSTESTUNIT_H__418934EE_BE03_4CDB_BC61_8305336B644D__INCLUDED_)
#define AFX_PLUSTESTUNIT_H__418934EE_BE03_4CDB_BC61_8305336B644D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <cppunit/TestSuite.h>
#include <string>
class CPlusTestUnit
{
public:
CPlusTestUnit();
virtual ~CPlusTestUnit();
static CppUnit::Test *suite();
static std::string plusSuiteName();
};
#endif // !defined(AFX_PLUSTESTUNIT_H__418934EE_BE03_4CDB_BC61_8305336B644D__INCLUDED_)
2) 编写测试用例类,如:CPlusTestCase
该类共有继承于: CppUnit::TestCase ,
如:class CPlusTestCase : public CppUnit::TestCase 。
需引入:<cppunit/extensions/HelperMacros.h>
a)在.h文件中定义测试环境:
CPPUNIT_TEST_SUITE(CPlusTestCase);
CPPUNIT_TEST_SUITE_END();
b)定义具体的测试函数,如:
void CPlusTestCase::testAdd()
{
CPlus plus;
int nResult = plus.Add(10, 20);
CPPUNIT_ASSERT_EQUAL(30, nResult);
}
c)然后将测试函数加到测试环境中:
CPPUNIT_TEST(testAdd);
d)将测试函数在.cpp中进行注册:
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(CPlusTestCase,
CPlusTestUnit::plusSuiteName());
3) 将测试用例在系统初始化函数中进行定义:
a) 先将系统自动生成的对话框注释掉,即将如下代码注释掉
CCppTestDlgDlg 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
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
b) 注册Testrunner对话框
首先添加引用: #include <cppunit/ui/mfc/TestRunner.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
添加对测试注册类的引用:#include "CPlusTestSuite.h"
添加Testrunner对话框
7. 运行
运行前需将所需的几个.dll放到相应的位置上,或者系统目录。