前言
CppUnit是一个开源的单元测试框架,支持Linux和Windows操作系统,在linux上可以直接进行源码编译,得到动态库和静态库,直接链接就可以正常使用,在Windows上可以使用VC直接进行编译,非常便于调试。CppUnit的源码框架被运用到了Java和Python等语言中,使用非常广泛,熟悉了一种语言下的CppUnit使用方法,其他语言测试框架也不在话下,本文以cppunit-1.12.1为例进行演示和说明。
一个例子
Linux下CppUnit源码编译和安装
- 解压源码文件到cppunit-1.12.1目录
- cd cppunit-1.12.1
- ./configure --prefix=安装路径(必须是绝对路径)
- make
- make install
编辑测试代码
一共三个文件main.cpp、simpleTest.h、simpleTest.c,目录下文件的组织结构如下所示:
三个文件的源码如下:
//main.cpp文件 #include "cppunit/TestResultCollector.h" #include "cppunit/TextOutputter.h" #include "cppunit/XmlOutputter.h" #include "cppunit/CompilerOutputter.h" #include "cppunit/TestResult.h" #include "cppunit/TestRunner.h" #include "cppunit/extensions/TestFactoryRegistry.h" #include <cstdlib> #include <ostream> int main() { CppUnit::TestResult r; CppUnit::TestResultCollector rc; r.addListener(&rc); // 准备好结果收集器 CppUnit::TestRunner runner; // 定义执行实体 runner.addTest(CppUnit::TestFactoryRegistry::getRegistry("alltest").makeTest()); runner.run(r); // 运行测试 //CppUnit::TextOutputter o(&rc, std::cout); //o.write(); // 将结果输出 //std::ofstream file; //file.open("./UnitTest.xml"); //CppUnit::XmlOutputter xo(&rc, file); //xo.write(); CppUnit::CompilerOutputter co(&rc, std::cout); co.write(); return rc.wasSuccessful() ? 0 : -1; }
//SimpleTest .h文件 #include "cppunit/extensions/HelperMacros.h" class SimpleTest : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(SimpleTest); CPPUNIT_TEST(test1); CPPUNIT_TEST(test2); CPPUNIT_TEST_SUITE_END(); public: void test1(); void test2(); };
//simpleTest.cpp文件 #include "simpleTest.h" #include <string> #include <iostream> #include "cppunit/TestCase.h" #include "cppunit/TestAssert.h" CPPUNIT_TEST_SUITE_NAMED_REGISTRATION(SimpleTest, "alltest"); void SimpleTest::test2() { CPPUNIT_ASSERT(3 == 3); } void SimpleTest::test1() { CPPUNIT_ASSERT(2 == 2); }
编译命令如下:
g++ main.cpp simpleTest.cpp -o test -I /home/chusiyong/cppunit/install/include -L /home/chusiyong/cppunit/install/lib -Wl,-Bstatic -lcppunit -Wl,-Bdynamic -ldl
运行可执行文件,结果如下:
OK (2)
表示所有用例都执行成功