Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing protected member with googletest

I'm confused regarding inheritance when googletesting. I have a class A that has protected attributes. If I want to access those i have to extend that class, but at the same time i also need to extend public ::testing::Test for the sole purpose of gtest.

What is the most elegant solution to this problem? Also I'm trying to avoid #define protected public

like image 334
jabk Avatar asked Oct 13 '14 09:10

jabk


2 Answers

To avoid leaving traces of tests in the tested class use multiple-inheritance with a fixture:

class ToBeTested
{
protected:
    bool SensitiveInternal(int p1, int p2); // Still needs testing
}

// Google-test:
class ToBeTestedFixture : public ToBeTested, public testing::Test
{
   // Empty - bridge to protected members for unit-testing
}

TEST_F(ToBeTestedFixture, TestSensitive)
{
    ASSERT_TRUE(SensitiveInternal(1, 1));
    ASSERT_FALSE(SensitiveInternal(-1, -1));
}
like image 194
user5227565 Avatar answered Oct 03 '22 07:10

user5227565


There is a FRIEND_TEST declaration, which is used in the header of tested class. Basically it defines the test as a friend of the class. In my use case, we disable all test includes when compiling in RELEASE mode, so it doesn't do any harm the real executable.

Have a look at this

like image 35
lisu Avatar answered Oct 03 '22 05:10

lisu