7

I have a BOOST_AUTO_TEST_CASE which needs a helper function. I could just make this a regular function and call it from within; but I'd rather somehow keep it local and private to the scope of the BOOST_AUTO_CASE. I'd also like to be able to declare vars which are in the scope of both the test case and the helper functions (e.g. const int serverCount = 10;).

If the test case was a class (and not a macro), I'd simply use a private member function. How do I do this (or the equivalent) for a Boost unit test case?

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
SRobertJames
  • 8,210
  • 14
  • 60
  • 107

1 Answers1

7

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.

TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
  • Thanks. Are the `BOOST_FIXTURE_TEST_CASE` added as methods to `TestContext`? Is there a way to write them within the `{}` scope of `TestContext`? For style and organization, I'm happier seeing everything within one set of `{}`. (Also helps with the IDE and code folding.) – SRobertJames May 28 '15 at 12:05
  • Most of my classes have a single test fixture `TestContext`, that's why I never needed an additional orgainizational scope. If you look into `unit_test_suite.hpp` you can find the definition of `BOOST_FIXTURE_TEST_CASE`. This might give you an idea whether it is possible or not. Better yet: Try it, what can go wrong? – TobiMcNamobi May 28 '15 at 12:18