DEV Community

Thibaut Andrieu
Thibaut Andrieu

Posted on

Tiny Tips : Testing protected method without using friendship in C++

Assume you have this class to test:

MyClass.h

class MyClass {
public:
    float publicMethod();
protected:
    float criticalInternalMethod();
};
Enter fullscreen mode Exit fullscreen mode

criticalInternalMethod() implement a complex business logic or algorithm, but it is too internal to make it part of public API. How to test it ?

With GoogleTest, you can use the FRIEND_TEST macro. But it requires putting google header in public API, and a macro in class definition.

What you can do instead is this:

MyClassTest.cpp

class MyClassTest : public MyClass
{
public:
    using MyClass::criticalInternalMethod;
};

TEST(MyClassShould, computeGoodResult)
{
    MyClassTest myClass;
    EXPECT_EQ(myClass.criticalInternalMethod(), 12);
}
Enter fullscreen mode Exit fullscreen mode

This doesn't work for private method, but at least it avoids polluting public header only for the sake of testing.

Top comments (1)

Collapse
 
serkzex profile image
Mujtaba Aldebes

This also dosn't work if MyClass is final, but nice tips.