lundi 27 avril 2020

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).

Aucun commentaire:

Enregistrer un commentaire