CppUnit Cookbook

Here is a short cookbook to help you get started. Note that all CppUnit types are defined in the CppUnit namespace. For brevity, the prefix CppUnit:: is omitted in the following examples.

Simple Test Case

You want to know whether your code is working. How do you do it? There are many ways. Stepping through a debugger or littering your code with stream output calls are two of the simpler ways, but they both have drawbacks. Stepping through your code is a good idea, but it is not automatic. You have to do it every time you make changes. Streaming out text is also fine, but it makes code ugly and it generates far more information than you need most of the time.

Tests in CppUnit can be run automatically. They are easy to set up and once you have written them, they are always there to help you keep confidence in the quality of your code.

To make a simple test, here is what you do:

Subclass the TestCase class. Override the method runTest (). When you want to check a value, call CPPUNIT_ASSERT (bool) and pass in an expression that is true if the test succeeds.

For example, to test the equality comparison for a Complex number class, write:

	class ComplexNumberTest : public TestCase { 
                    ComplexNumberTest (string name) : TestCase (name) {}
        void        runTest () {
                        CPPUNIT_ASSERT (Complex (10, 1) == Complex (10, 1));
                        CPPUNIT_ASSERT (!(Complex (1, 1) == Complex (2, 2)));

That was a very simple test. Ordinarily, you'll have many little test cases that you'll want to run on the same set of objects. To do this, use a fixture.



A fixture is a known set of objects that serves as a base for a set of test cases. Fixtures come in very handy when you are testing as you develop. Let's try out this style of development and learn about fixtures along the away. Suppose that we are really developing a complex number class. Let's start by defining a empty class named Complex.

	class Complex {}; 

Now create an instance of ComplexNumberTest above, compile the code and see what happens. The first thing we notice is a few compiler errors. The test uses operator==, but it is not defined. Let's fix that.

	bool operator== (const Complex& a, const Complex& b) { return true; }

Now compile the test, and run it. This time it compiles but the test fails. We need a bit more to get an operator== working correctly, so we revisit the code.

	class Complex { 
        friend bool operator== (const Complex& a, const Complex& b);
        double      real, imaginary;
                    Complex ( double r, double i = 0 ) : real(r),imaginary(i) {}

        bool operator== (const Complex& a, const Complex& b)
        { return eq(a.real,b.real) && eq(a.imaginary,b.imaginary); }

If we compile now and run our test it will pass.

Now we are ready to add new operations and new tests. At this point a fixture would be handy. We would probably be better off when doing our tests if we decided to instantiate three or four complex numbers and reuse them across our tests.

Here is how we do it:

  1. Add member variables for each part of the fixture
  2. Override "setUp ()" to initialize the variables
  3. Override "tearDown ()" to release any permanent resources you allocated in "setUp ()"
	class ComplexNumberTest : public TestCase  {
        Complex 	*m_10_1, *m_1_1; *m_11_2;
	void		setUp ()  {
			    m_10_1 = new Complex (10, 1);
			    m_1_1  = new Complex (1, 1);
			    m_11_2  = new Complex (11, 2);  
	void		tearDown ()  {
			    delete m_10_1, delete m_1_1, delete m_11_2;

Once we have this fixture, we can add the complex addition test case any any others that we need over the course of our development.


Test Case

How do you write and invoke individual tests using a fixture?

There are two steps to this process:

  1. Write the test case as a method in the fixture class
  2. Create a TestCaller which runs that particular method

Here is our test case class with a few extra case methods:

	class ComplexNumberTest : public TestCase  {
        Complex 	*m_10_1, *m_1_1; *m_11_2;
	void		setUp ()  {
			    m_10_1 = new Complex (10, 1);
			    m_1_1  = new Complex (1, 1);
			    m_11_2 = new Complex (11, 2);  
	void		tearDown ()  {
			    delete m_10_1, delete m_1_1, delete m_11_2;
	void		testEquality ()  {
			    CPPUNIT_ASSERT (*m_10_1 == *m_10_1);
			    CPPUNIT_ASSERT (!(*m_10_1 == *m_11_2));
	void		testAddition ()  {
			    CPPUNIT_ASSERT (*m_10_1 + *m_1_1 == *m_11_2);

One may create and run instances for each test case like this:

	TestCaller<ComplexNumberTest> test("testEquality", &ComplexNumberTest::testEquality); (); 

The second argument to the test caller constructor is the address of a method on ComplexNumberTest. When the test caller is run, that specific method will be run. This is not a useful thing to do, however, as no diagnostics will be displayed. One will normally use a TestRunner (see below) to display the results.

Once you have several tests, organize them into a suite.



How do you set up your tests so that you can run them all at once?

CppUnit provides a TestSuite class that runs any number of TestCases together. We saw, above, how to run a single test case. To create a suite of two or more tests, you do the following:

	TestSuite suite;
	TestResult result;
	suite.addTest (new TestCaller<ComplexNumberTest>("testEquality", &ComplexNumberTest::testEquality));
	suite.addTest (new TestCaller<ComplexNumberTest>("testAddition", &ComplexNumberTest::testAddition)); (&result);

TestSuites don't only have to contain callers for TestCases. They can contain any object that implements the Test interface. For example, you can create a TestSuite in your code and I can create one in mine, and we can run them together by creating a TestSuite that contains both:

	TestSuite suite;
	TestResult result;
	suite.addTest (ComplexNumberTest::suite ());
	suite.addTest (SurrealNumberTest::suite ()); (&result);



FIXME: check over; MSVC6 only. How do you run your tests and collect their results?

Once you have a test suite, you'll want to run it. CppUnit provides tools to define the suite to be run and to display its results. You make your suite accessible to a TestRunner program with a static method suite that returns a test suite.
For example, to make a ComplexNumberTest suite available to a TestRunner, add the following code to ComplexNumberTest:

	public: static Test *suite ()  {
	    TestSuite *suiteOfTests = new TestSuite;
	    suiteOfTests->addTest (new TestCaller<ComplexNumberTest>("testEquality", testEquality));
	    suiteOfTests->addTest (new TestCaller<ComplexNumberTest>("testAddition", testAddition));
            return suiteOfTests;

To use the text version, include the header file for the test in TestRunner.cpp:

	#include "ExampleTestCase.h"
	#include "ComplexNumberTest.h"

And add a call to "addTest (string, Test *)" in the "main ()" function:

	int main (int ac, char **av)  {
	    TestRunner runner;
	    runner.addTest (ExampleTestCase::suite ());
	    runner.addTest (ComplexNumberTest::suite ()); ();
	    return 0;

The TestRunner will run the tests. If all the tests pass, you'll get an informative message. If any fail, you'll get the following information:

  1. The name of the test case that failed
  2. The name of the source file that contains the test
  3. The line number where the failure occurred
  4. All of the text inside the call to CPPUNIT_ASSERT which detected the failure

CppUnit distinguishes between failures and errors. A failure is anticipated and checked for with assertions. Errors are unanticipated problems like division by zero and other exceptions thrown by the C++ runtime or your code.

Original version by Michael Feathers, with small changes - e.g. removal of GUI docs. The example has to be adjusted to the current library structure, and possibly be setup in the examples directory.