Karthick S Karthick S - 1 month ago 13
C++ Question

Is using FRIEND_TEST the right thing to do?

When I look into the implementation of FRIEND_TEST at https://github.com/google/googletest/blob/master/googletest/include/gtest/gtest_prod.h, I see the following:

#ifndef GTEST_INCLUDE_GTEST_GTEST_PROD_H_
#define GTEST_INCLUDE_GTEST_GTEST_PROD_H_
// When you need to test the private or protected members of a class,
// use the FRIEND_TEST macro to declare your tests as friends of the
// class. For example:
//
// class MyClass {
// private:
// void MyMethod();
// FRIEND_TEST(MyClassTest, MyMethod);
// };
//
// class MyClassTest : public testing::Test {
// // ...
// };
//
// TEST_F(MyClassTest, MyMethod) {
// // Can call MyClass::MyMethod() here.
// }
#define FRIEND_TEST(test_case_name, test_name)\
friend class test_case_name##_##test_name##_Test
#endif


If my understanding is correct, the test class is made a child of the production class unconditionally. This would make the production class dependent on the test class. In effect, the production code will contain my test libraries too.

I am not sure if this is the right thing to do.

Am I missing something here or should this be compiled conditionally only?

Thanks.

Answer

I don't read it like that. You can make a made up non-existing class a friend of your production class if you want. It's harmless, and it certainly doesn't introduce a dependency or add testing code to your production code.

class Production
{
   friend class WibbleWibble;
   ...
};

This code is perfectly correct even if WibbleWibble doesn't exist. So there is no dependency.

Comments