Second, write unit test code
In CPPUnit, each test case uses a class that is typically used to test a module if the module is a class, just right corresponding to this test case.
Definition class:
Each test case class must inherit from cppUnit_ns :: testfixture. Such as:
Class Sampletestcase: PUBLIC CPPUNIT_NS :: TestFixTure
And, this class also needs to define a pair of macros:
CPPUNIT_TEST_SUITE (SAMPLETESTCASE);
CPPUNIT_TEST_SUITE_END ();
This is used to define the test methods included in this test class. Moreover, a macro is also required to identify the test class in the source program implemented:
CPPUNIT_TEST_SUITE_REGISTRATION (Sampletestcase);
In addition, each class can also achieve two methods: Setup (), Teardown (). The first method is called before the test method of running this class, and the second method is called after the test method of running this class. For example, if this test class needs to operate information in a file, you typically need to open the specified file before running the test method, which can be implemented in Setup (). After the test is completed, it needs to be turned off to turn the open file, which can be implemented in Teardown (). The prototype of these two methods is:
Void setup ();
Void Teardown ();
Define test method
Each test method is used to test a function, usually correspond to a disclosure method of the subject being tested. For example, there is a FOO () method in the SAMPLE class, and a foo () method can also be declared in the test class SampleTestCase. Note that it is highly recommended to use the same name so that it is easy to maintain.
Each test method needs to add a definition in the CPPUnit_Test_Suite macro in the class so that CPPUnit can discover the test method, such as:
CPPUNIT_TEST (FOO);
After defining the test method, you can write a unit test code within the method. Both the unit test framework uses the asserted test method, namely a expression, checking if the result is true, true, is expressed. In CPPUnit, the macros used to verify the tests include:
CPPUNIT_ASSERT (EXPR): Check if the expression expr is true, true passes, false false.
CPPUNIT_ASSERT_THOW (EXPR, Exception): Check if the expression expr is throws an exception type Exception, and if you throw an exception of the specified type, it is tested.
CPPUNIT_ASSERT_MESSAGE (MESSAGE, EXPR): Similar to CPPUnit_assert, but outputs Message when not passed.
CPPUNIT_FAIL (Message): Mandatory does not pass the test, and outputs the message Message.