Test Setup and Teardown

Frequently, a group of related tests all wish to run in the same environment. To do this, it's helpful to know a bit of what goes behind the scenes. Just before a Suite (or Registry) runs a test, it first constructs an object whose type is the test class. It then calls run() on the newly constructed object. Finally, it destroys the newly-constructed object, calling its destructor. (It calls the destructor even if an assertion failed while running the test.)

Thus, whenever a test has to set up its environment, or clean up the environment after running, you have a choice to do that in the constructor/destructor or in the run() function. In particular, it's a very good idea to do cleanup in destructors instead of at the end of run(): since destructors are run even in the case of failure, this makes it easier to avoid cascade failures. (Recall that run() aborts after the first assertion failure, so you can't depend on code there always being executed.)

In particular, if a group of related tests all want their environment set up in the same way, the easy way to do this is for them all to inherit from a common base class whose constructor sets up the environment appropriately. (And whose destructor cleans up appropriately, of course!) This base class also provides a convenient place to stash helper functions that are used by multiple tests.


david carlton <carlton@bactrian.org>