CppUnit source code parsing

Foreword

  CppUnit is an open source unit testing framework, support for Linux and Windows operating systems, can be performed on linux direct source compiler, get the dynamic and static libraries, a direct link can be used normally, you can use VC directly on Windows to compile, very easy to debug. CppUnit source framework is applied to the Java and Python languages, is widely used, familiar with the use of CppUnit in a language, other languages ​​also mention testing framework, this paper cppunit-1.12.1 as an example and demonstration instructions.

 

one example

Linux source code to compile and install under CppUnit

  • Extract the source files to cppunit-1.12.1 directory
  • cd cppunit-1.12.1
  • ./configure --prefix = installation path (must be absolute path)
  • make 
  • make install

 

Edit test code

A total of three files main.cpp, organization simpleTest.h, simpleTest.c, directory file is as follows:

Three source files as follows:

//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); // run the test

    //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);
}

Compiler command is as follows:

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  

Run the executable file with the following results:

OK (2)  

It means that all the use cases are executed successfully

 

Guess you like

Origin www.cnblogs.com/chusiyong/p/11403681.html