Search code examples
c++googletestprotected

Accessing protected variable in googletest


I have this class testC that is meant for google testing

class testC : public A { };

and then bunch of TEST's that are in the same file.

TEST(test_case_name, test_name) {
 ... test body ...
}

A is structured like this

class A{

protected:
   B b;
public:
   //constructors
   //destructor
   //member functions

Q: How can I access b in all the TEST(){} functions through testC?

I tried to do a getter in testC

public:
  testC getTest(){
      testC test;
      return test;
  }

and i also tried with returning a reference, but no luck...


Solution

  • Try the FRIEND_TEST macro provided by googletest. Have a look in the advanced guide under Private class members.

    You have to declare the test as a friend of the code under test. If I'm not mistaken you have to declare the friendship for all tests that want to access protected members.

    class MySystemUnderTest
    {
        #ifdef _MY_UNIT_TEST
        FRIEND_TEST(MySystemUnderTest_test, functionA_prereq_expected);
        FRIEND_TEST(MySystemUnderTest_test, functionB_prereq_expected);
        #endif
    
        ...
    };
    

    In the example above I use the preprocessor symbol _MY_UNIT_TEST to remove the declaration from productive code. The methods functionA_prereq_expected and functionB_prereq_expected would be defined in the test fixture MySystemUnderTest_test.

    You have to add the FRIEND_TEST declaration in the code under test. That's the price you have to pay if you want to test against protected / private members.