CppUnit Basics

The common way to group tests with CppUnit is to create a class and put the tests in appropriate methods. By deriving the test class from CppUnit::TestFixture you get the functionality to register and control the tests.

class Calculator_test : public CppUnit::TestFixture

Most of the implementation code is available with macros. To create the code for a method test_add() you would use the following sequence within the class body:

   CPPUNIT_TEST_SUITE( Calculator_test );


   void test_add();

CppUnit provides a mechanism to automatically register the tests. This is done with a static variable hidden in a macro:


The test method itself verifies the actual value against the expectation and throws an exception if they don't match. CppUnit provides a set of macros to handle the common cases.

void Calculator_test::test_add()
  Calculator calc(100);
  CPPUNIT_ASSERT_EQUAL(123, calc.add(23));

To finally run all the tests you have to create the desired environment, register the tests and start the process:

  CppUnit::TextUi::TestRunner runner;
  CppUnit::TestFactory &registry = CppUnit::TestFactoryRegistry::getRegistry();
  return runner.run() ? 0 : 1;

cppunit.cpp contains the complete source code.

Next: Using Verifying Test Cases

Table of contents

 All Classes Namespaces Files Functions Variables Typedefs Friends Defines

Generated on Tue Jan 5 18:03:33 2010 for mockpp-tutorial by  doxygen 1.6.1