c++testinggoogletestboost-testgunit

Writing unit tests which may access private/protectedstate


I use Boost Test for unit tests. I typically have a fixture struct:

class ClassBeingTested
{
protected:
    int _x;             // Want to access this directly in my unit tests
};

struct TestFixture : public ClassBeingTested
{
    // I can access ClassBeingTested::_x here but it means i have to add getters for each test to call
    ClassBeingTested _bla;
};

However, even if my fixture inherits from ClassBeingTested or uses a friend relationship I cannot access private/protected methods/state from each individual test:

BOOST_FIXTURE_TEST_CASE(test1, TestFixture)
{
    _bla.doSomething();
    BOOST_REQUIRE_EQUAL(_bla.x, 10);    // Compiler error. I cannot access ClassBeingTested::_x here
}

only the fixture, which means I have to add a new getter (or test) for each access I wish to make.

Is there any way to achieve this? I have to add public getter methods to ClassBeingTested which are only used by tests, which isn't ideal.

(Please no replies of 'test using the public interface', that's not always possible).


Solution

  • You can make a friend test buddy, struct ClassBeingTestedBuddy; with friend struct ClassBeingTestedBuddy; in the class ClassBeingTested.

    Have the test buddy class expose all the protected or private variables or methods that you need for all your tests.

    It'd look like...

    struct ClassBeingTestedBuddy {
        ClassBeingTested* obj;
        ClassBeingTestedBuddy(ClassBeingTested* obj_)
          : obj{obj_} {}
    };
    

    ...plus anything else you'd want to expose.

    This is but one way of allowing the tests a bridge to the protected and private data and methods. But since it is all code in your project, for your testing use, it is a reasonable way of getting the test code access without too much instrumenting your actual code.