在Project中加入一個(gè)類,取名CArithmeticTestCase,CArithmeticTestCase從CppUnit::TestCase繼承,代碼如下:
//ArithmeticTestCase.h
#pragma once
#include "cppunit/extensions/HelperMacros.h"
class CArithmeticCase : public CppUnit::TestCase
{
CPPUNIT_TEST_SUITE(CArithmeticCase);
CPPUNIT_TEST(testAdd);
CPPUNIT_TEST(testSub);
CPPUNIT_TEST(testMul);
CPPUNIT_TEST(testDiv);
CPPUNIT_TEST_SUITE_END();
public:
CArithmeticCase(void);
~CArithmeticCase(void);
void testAdd();
void testSub();
void testMul();
void testDiv();
virtual void setUp();
virtual void tearDown();
};
// ArithmeticTestCase.cpp
#include "StdAfx.h"
#include "ArithmeticTestCase.h"
#include "Plus.h"
CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(CArithmeticTestCase,"MyArithmeticTest");
CArithmeticTestCase::CArithmeticTestCase(void)
{
}
CArithmeticTestCase::~CArithmeticTestCase(void)
{
}
void CArithmeticTestCase::testAdd()
{
CArithmetic plus;
int nResult = plus.Add(10, 20);
CPPUNIT_ASSERT_EQUAL(30, nResult);
}
void CArithmeticTestCase::testSub()
{
CArithmetic plus;
int nResult = plus.Sub(10, 20);
CPPUNIT_ASSERT_EQUAL(-10, nResult);
}
void CArithmeticTestCase::testMul()
{
CArithmetic plus;
int nResult = plus.Mul(10, 20);
CPPUNIT_ASSERT_EQUAL(200, nResult);
}
void CArithmeticTestCase::testDiv()
{
CArithmetic plus;
double fResult = plus.Div(10, 20);
CPPUNIT_ASSERT_DOUBLES_EQUAL(0.5, fResult,0.000001);
}
void CArithmeticTestCase::setUp()
{
//初始化一些共用信息,比如全局變量,資源等。
TRACE("Enter CPlusTestCase::setUp()
");
}
void CArithmeticTestCase::tearDown()
{
//析構(gòu)處理一些信息,比如釋放資源
TRACE("Enter CPlusTest::tearDown()
");
}
測試代碼編寫
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/mfc/TestRunner.h>
#pragma comment(lib, "cppunitd.lib")
#pragma comment(lib, "testrunnerud.lib")//可以加載靜態(tài)庫,比動(dòng)態(tài)庫DEBUG版本,具體參考cppunit-1.12.1lib下的文件。
CppUnit::MfcUi::TestRunner runner;
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry("MyArithmeticTest");
runner.addTest(registry.makeTest());
runner.run();