I've been racking my brain trying to think of the best way to access a protected member function from some test code in C++, here's my problem:
//in Foo.h
Class Foo
{
protected:
void DoSomething(Data data);
}
//in Blah.h
Class Blah
{
public:
Foo foo;
Data data;
};
//in test code...
Blah blah;
blah.foo.DoSomething(blah.data); // Here's my problem!
Some possible solutions so far:
All advice/insight/opinions are most welcome!
Thanks
Ok, since you said it is only a test code I am going to suggest something seriously hacky but would work:
There is a way which is completely allowed by the Standard.
Read the Hidden features of C++ entry for an explanation.
You may write a macro for your convenience (the parenthesis are there so that you can use this macro also for types that have a comma, like
vector<pair<A, B>>
):The matter now becomes
Use wrapper as follows:
I've done
Then compile your unit tests with g++ -D TEST.
On the one hand, don't do that.
On the other hand, here's a gamble:
8-)
But seriously, why is
DoSomething()
protected? Probably because calling it from external code can break something. In which case, you shouldn't be calling it from your tests.Rather than ifdefing
private
topublic
, consider ifdefing friendship, or better yet think if that function really needs to belong to that class, maybe it would suffice to have something in a named/unnamed namespace in a cpp, and then declared in a test project.Anyway, check this link, maybe your testing framework would provide similar functionality.
EDIT: Did you consider inheriting your test class from your real class?