Luckily there is a solution for this right in the Boost test framework: Fixtures. There are different types of fixtures but in your case the per test case fixture seems to fit.
#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>
struct TestContext {
TestContext() : testVar( 0 ) { BOOST_TEST_MESSAGE( "setup fixture" ); }
~TestContext() { BOOST_TEST_MESSAGE( "teardown fixture" ); }
int testVar;
void helperMethod(int x, double y)
{
testVar = x * (int)y;
}
};
BOOST_FIXTURE_TEST_CASE( test_case1, TestContext )
{
BOOST_CHECK( testVar == 1 );
++testVar;
}
BOOST_FIXTURE_TEST_CASE( test_case2, TestContext )
{
helperMethod(2, 3.1);
// ...
}
testVar
is accessible in the test case as well as in the TestContext
class / struct. TestContext
's constructor and destructor are called right before and after each test case respectively. They are not needed but can come in handy if you have to manage memory for example. In particular each test case is run with its own fresh instance of TestContext
.
Update: Still valid for Boost 1.66, link updated.