Better Unit tests for C++

From OPeNDAP Documentation
Revision as of 18:08, 3 January 2022 by Jimg (talk | contribs) (Parts of a CPPUNIT test suite)

We use CPPUNIT for C++ unit tests. But most of our tests don't take advantage of CPPUNIT's best feature - its extensive set of test and assertion macros. This how-to explores some of the macros using a real test that was rewritten to be more useful and easier to read (and a bit shorter).

Parts of a CPPUNIT test suite

We want to write test suites and not tests because it is better to run a collection tests where each test runs regardless of whether the previous tests pass or fail. A single test can easily hide multiple (possibly related) problems because it stops running at the first failure. But it's hard to write tests that look for exceptions and other complex conditions without repeating lots of 'boilerplate' code. CPPUNIT macros to the rescue.

It is important to make each test in the test suite independent of the other tests.

But first, the parts of a test suite:

The CPPUNIT headers, the header for the class under test, headers that header needs and other stuff for the tests
Class definition
Each test suite is a class. The class typically contains an instance (or pointer to) of the class to be tested.
Class constructor and destructor
Often these can be set to the default. If they are used to initialize class members, that initialization will be done once for the entire test suite.
Setup and Teardown methods
These methods are run before and after each test in the test suite.