在Project中加入一个类,取名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()
{
//析构处理一些信息,比如释放资源
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")//可以加载静态库,比动态库DEBUG版本,具体参考cppunit-1.12.1lib下的文件。
CppUnit::MfcUi::TestRunner runner;
CppUnit::TestFactoryRegistry ®istry = CppUnit::TestFactoryRegistry::getRegistry("MyArithmeticTest");
runner.addTest(registry.makeTest());
runner.run();