一,编译生成 lib,dll 文件
1.下载 CppUnit 源文件(这里用 1.12.0 版本,download from here: http://sourceforge.net/projects/cppunit/files/cppunit/ )
2.解压后,进入其中的 src 目录(cppunit-1.12.0\src),打开 CppUnitLibraries.dsw,
编译其中的几个工程:
cppunit:
生成 cppunitd.lib (debug 版本)
生成 cppunit.lib (release 版本)
cppunit_dll:
生成 cppunitd_dll.lib, cppunitd_dll.dll (debug 版本)
生成 cppunit_dll.lib, cppunit_dll.dll (release 版本)
TestRunner:
生成 testrunnerud.dll, testrunnerud.lib (debug 版本)
生成 testrunneru.dll, testrunneru.lib (release 版本)
TestPlugInRunner:
生成 TestPlugInRunnerd.exe
DllPlugInTester:
生成 DllPlugInTesterd.exe
主要是为了提取这三个文件(debug 情况下):
cppunitd.lib, cppunitd_dll.lib, testrunnerud.dll
这样我们就可加入到后面要新建的测试工程中
二,设置 Visual Studio 2008
打开‘Tools’->’Options…’->’Projects and Solutions’->’VC++ Directories’。
在’Include files’加入:cppunit-1.12.0/include的路径
在’Library files’加入:cppunit-1.12.0/lib的路径
在’Source files’加入:cppunit-1.12.0/src的路径
三,实例程序
//待被测试的类 //myClass.h #ifndef MYCLASS_H #define MYCLASS_H class myClass { public: int add(int, int); int sub(int, int); }; #endif //myClass.cpp #include "myClass.h" int myClass::add(int a, int b) { return a+b; } int myClass::sub(int a, int b) { return a-b; }
//测试案例的类 //CTestMyClass.h #ifndef CTESTMYCLASS_H #define CTESTMYCLASS_H #include "cppunit/TestCaller.h" #include "cppunit/extensions/HelperMacros.h" #include "cppunit/TestSuite.h" #include "myClass.h" #pragma comment(lib,"cppunitd.lib") #pragma comment(lib,"testrunnerd.lib") class CTestMyClass:public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(CTestMyClass); CPPUNIT_TEST(TestCase_1); CPPUNIT_TEST(TestCase_2); CPPUNIT_TEST(TestCase_3); CPPUNIT_TEST_SUITE_END(); public: void setUp(); void tearDown(); void CTestMyClass::TestCase_1(); void CTestMyClass::TestCase_2(); void CTestMyClass::TestCase_3(); private: myClass *mc; }; #endif //CTestMyClass.cpp #include "CTestMyClass.h" CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(CTestMyClass, "mytest"); void CTestMyClass::setUp() { mc = new myClass; } void CTestMyClass::tearDown() { delete mc; } void CTestMyClass::TestCase_1() { CPPUNIT_ASSERT_EQUAL(5,mc->add(2,3)); } void CTestMyClass::TestCase_2() { CPPUNIT_ASSERT_EQUAL(-1,mc->sub(2,3)); } void CTestMyClass::TestCase_3() { int a = 4; CPPUNIT_ASSERT(4 == a); }
//运行测试用例 //Main.cpp #include "CTestMyClass.h" #include "cppunit/TestCaller.h" #include "cppunit/extensions/HelperMacros.h" #include "cppunit/TestSuite.h" #include "cppunit/ui/text/TestRunner.h" #include "cppunit/TextOutputter.h" #include "cppunit/CompilerOutputter.h" #include <iostream> #include <fstream> using namespace std; int main(int argc, char* argv[]) { CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry("mytest").makeTest(); CppUnit::TextUi::TestRunner runner; runner.addTest(suite); ofstream outfile; outfile.open("./result.txt",ios::out); runner.setOutputter(new CppUnit::TextOutputter(&runner.result(),outfile)); runner.run(); return 0; }