Search code examples
c++methodsvisibilitygoogletestfixtures

How to pass a test fixture to a helper function in C++ GTest


I have a protected static method in my test fixture I wish to call from a helper function, instead of from the unit test function itself.

class Fixture
{
  ...
protected:
    static void fixture_func( int foo );
};

void helper_func( int bar ) {
  Fixture::fixture_func( bar );
}

TEST_F( Fixture, example_test ) {
  fixture_func( 0 );  //Line 1: This is how you would normally call the method
  
  helper_func( 0 );  //Line 2: This is how I need to call the method
}

When I try Line 2, I obviously get an error that the method is 'inaccessible' because its a protected method within fixture. How can I somehow pass the test fixture to helper_func, or else put fixture_func within the scope of helper_func?

If you're wondering, simply calling fixture func from the unit test itself is not an option because I am designing a test framework meant to simplify the use of fixture_func for a particular purpose. I also do not have the ability to make non-trivial changes to fixture.


Solution

  • You cannot call protected nor private methods from outside of a class, no matter if that method is static or if the calling function is C-style one.

    In any case, you would need the class scope Fixture:: before fixture_func:

    void helper_func( int bar ) {
      Fixture::fixture_func( bar );
    }
    

    You need to make fixture_func become public somehow, you may try:

    class FixtureExpanded : public Fixture { };
    void helper_func( int bar ) {
      FixtureExpanded::fixture_func( bar );
    }