Boost C++ Libraries

...one of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

Global fixture
PrevUpHomeNext

Any global initialization that needs to be performed every time testing begins or a global cleanup that is to be performed once testing is finished is called a global fixture. The Unit Test Framework global fixture design is based on the generic test class fixture model. The global fixture design allows any number of global fixtures to be defined in any test file that constitutes a test module. Though some initialization can be implemented in the test module initialization function, there are several reasons to prefer the global fixture approach:

  • There is no place for cleanup/teardown operations in the initialization function.
  • Unlike the initialization function, the global fixture setup method invocation is guarded by the execution monitor. That means that all uncaught errors that occur during initialization are properly reported.
  • Any number of different global fixtures can be defined, which allows you to split initialization code by category.
  • The fixture allows you to place matching setup/teardown code in close vicinity in your test module code.
  • If the whole test tree is constructed automatically the initialization function is empty and auto-generated by the Unit Test Framework. To introduce the initialization function can be more work than the use of a global fixture facility, while global fixture is more to the point.
  • Since all fixtures follow the same generic model you can easily switch from local per test case fixtures to the global one.
  • If you are using the interactive test runner (non-supplied yet) global test fixtures are applied to every run, while an initialization function is executed only once during a test module startup (just make sure that it's what you really want).

To define a global test module fixture you need to implement a class that matched generic fixture model and passed it as an argument to the macro BOOST_GLOBAL_FIXTURE.

BOOST_GLOBAL_FIXTURE(fixture_name);

The statement, that performs global fixture definition, has to reside at a test file scope.

Example: Global fixture

Code

#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
#include <iostream>

//____________________________________________________________________________//

struct MyConfig {
  MyConfig()   { std::cout << "global setup\n"; }
  ~MyConfig()  { std::cout << "global teardown\n"; }
};

//____________________________________________________________________________//

BOOST_GLOBAL_FIXTURE( MyConfig );

BOOST_AUTO_TEST_CASE( test_case )
{
  BOOST_TEST( true );
}

Output

> example
global setup
Running 1 test case...
global teardown

*** No errors detected

PrevUpHomeNext