Writing a Collection of Tests

Now that you've written a test, you'd probably like to run it. There are a couple of layers here: you'll typically want to group your tests into suites, and your suites into a registry.

First, suites. Say you've written a bunch of tests for your spiffy new Stack class: SinglePush, PushPop, EmptyPop, etc. Group these into a namespace, called perhaps StackTest. Then, within your namespace, create a class that should inherit from UnitTest::Suite. Its constructor should call the add() function repeatedly, passing each test as a template argument. Here's an example:

    namespace StackTest {
      class SinglePush { /* ... */ };
      class PushPop { /* ... */ };
      class EmptyPop { /* ... */ };

      class All : public UnitTest::Suite {
        All() {

Next, you should expose StackTest::All to the outside world as follows:

    UnitTest::TestPtr stackTests() {
      return UnitTest::createSuite<StackTest::All>();

That's the first part of grouping your tests together. The other part is to write a program that runs your stack tests, as well as the tests for your other classes. To do this, write a main() function. This should create a UnitTest::Registry, add each of the suites to it, and then call run() on the registry. Here's an example:

    int main(int argc, char **argv) {
      UnitTest::Registry tests;

      tests.add(stackTests(), "stack");
      tests.add(queueTests(), "queue");

      return tests.run(argc, argv);

If you compile and run this, it will run all of your tests. It will print out a dot for each passing test; for each failing test, it will print out the failing assertion. It will print out the total number of passes and failures; it will return 0 if all the tests passed, or 1 if at least one failed.

If you only want to run tests from some of the suites, you can specify the suites that you want to run as an argument to your program. In the above situation, for example, if you invoke the program with the argument stack, it will only run the stack tests.

The class UnitTest::Suite is defined in the header file unittest/UnitTest.hpp; the class UnitTest::Registry is defined in the header file unittest/Registry.hpp.

david carlton <carlton@bactrian.org>