I'm looking for a "clean" way of accessing some private member variables in a test context without touching the original code. I was thinking about implementing a friendship relation with the test class, but for some reason I do not understand it still requires a protected accessor in order to work. Why is it like that? Is there any other way to access the private member variable?
class A
{
protected: // this works
// private: // this DOES not work
int a;
};
class TestableA : public A
{
friend class TestA;
};
class TestA
{
void test()
{
m_a.a = 100;
}
TestableA m_a;
};
You can't access a private variable from a derived class, only protecteds.
TestA
is a friend of TestableA
, so it can see everything TestableA
contains. But if a
is private, you can't access it in TestableA
.
You have several options:
A
directly. You can even do it with a macro, which only effects the debug/test build.For more information about this topic, there's a good presentation called Friendship in Service of Testing