这个CppUnit包是POCO中的CppUnit的简化版本,但是开展测试C++的测试用例来说已经足够了。
2、代码示例
类foo,完成加法,等功能
class CFoo { public: int a(int a, int b) { return a + b; } char c() { return 'c'; } void t() { throw std::exception("foo exception."); } };
#include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" class CFooTest: public CppUnit::TestCase { public: CFooTest(const std::string& name):CppUnit::TestCase(name) { } ~CFooTest() { } void testa() { CFoo foo; int a = foo.a(1,2); assert(3 == a); char *p = NULL; assertEqual(1.3,1.3); } void testc() { CFoo foo; assert(foo.c() == 'c'); } void testt() { CFoo foo; try { foo.t(); fail("will not run."); } catch (std::exception& ) { } } void testThrow() { CFoo foo; foo.t(); } void setUp() { } void tearDown() { } static CppUnit::Test* suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("CFooTestSuite"); CppUnit_addTest(pSuite,CFooTest,testa); CppUnit_addTest(pSuite,CFooTest,testc); CppUnit_addTest(pSuite,CFooTest,testt); CppUnit_addTest(pSuite,CFooTest,testThrow); return pSuite; } };
#include "CppUnit/TestRunner.h" #include "CppUnit/TextTestResult.h" #include "CppUnit/TestSuite.h" int main() { /* 终极suite,将其他suite都包到里面来 */ CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("main"); pSuite->addTest(CFooTest::suite()); // pSuite->addTest Other suites. // TestRunner用于运行测试用例 CppUnit::TestRunner runnre; runnre.addTest("main",pSuite); std::vector<std::string> args; args.push_back("drive"); args.push_back("-all"); args.push_back("-print"); runnre.run(args); return 0; }