在VC6 中使用Cppunit总结
2009-7-11
下载、并编译Cppunit
从http://sourceforge.net/projects/cppunit CppUnit的源码包. 目录结构如下:
- include: CppUnit头文件;
- src: CppUnit源代码目录;
- lib:存放编译好的库;
在src/目录下, 使用VC编译CppUnitLibraries.dsw工程文件。将在lib目录下生成相关的库文件。
创建测试工程
创建console类型的工程。在工程中进行以下设置:
- 在project settings/c++/preprocessor 中设置头文件路径,在project settings/link/input中设置库文件路径及库文件名。
- 使能RTTI开关;
- 在Use run-time library一栏中,针对debug和release分别设置为‘Debug Multithreaded DLL’和‘Multithreaded DLL’。
用下面这段代码替换生成的主程序文件
#include "stdafx.h"
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
int main(int argc, char* argv[])
{
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
runner.addTest( suite );
// Change the default outputter to a compiler error format outputter
runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
std::cerr ) );
// Run the tests.
bool wasSucessful = runner.run();
// Return error code 1 if the one of test failed.
return wasSucessful ? 0 : 1;
}
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>
int main(int argc, char* argv[])
{
// Get the top level suite from the registry
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
// Adds the test to the list of test to run
CppUnit::TextUi::TestRunner runner;
runner.addTest( suite );
// Change the default outputter to a compiler error format outputter
runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(),
std::cerr ) );
// Run the tests.
bool wasSucessful = runner.run();
// Return error code 1 if the one of test failed.
return wasSucessful ? 0 : 1;
}
从CppUnit::TestFixture类派生出测试类,然后使用以下宏来定义TestSuite和TestCase:
- CPPUNIT_TEST_SUITE() 开始创建一个TestSuite;
- CPPUNIT_TEST() 添加TestCase;
- CPPUNIT_TEST_SUITE_END() 结束创建TestSuite;
- CPPUNIT_TEST_SUITE_NAMED_REGISTRATION() 注册TestSuite;
这里使用的是文本方式
创建被测试工程
创建 static library 类型的Project,在其中加入待测试的代码。
建立工程依赖关系。