Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make google-test classes friends with my classes?

I heard there is a possibility to enable google-test TestCase classes friends to my classes, thus enabling tests to access my private/protected members.

How to accomplish that?

like image 782
pajton Avatar asked Mar 07 '10 13:03

pajton


3 Answers

Try this (straight from Google Test docs...):

FRIEND_TEST(TestCaseName, TestName);

For example:

// foo.h
#include <gtest/gtest_prod.h>

// Defines FRIEND_TEST.
class Foo {
  ...
 private:
  FRIEND_TEST(FooTest, BarReturnsZeroOnNull);
  int Bar(void* x);
};

// foo_test.cc
...
TEST(FooTest, BarReturnsZeroOnNull) {
  Foo foo;
  EXPECT_EQ(0, foo.Bar(NULL));
  // Uses Foo's private member Bar().
}
like image 61
hobbit Avatar answered Nov 20 '22 20:11

hobbit


I know this is old but I was searching for the same answer today. "gtest_prod.h" just introduces a simple macro to reference test classes.

#define FRIEND_TEST(test_case_name, test_name)\
friend class test_case_name##_##test_name##_Test

So FRIEND_TEST(FooTest, BarReturnsZeroOnNull); is equivalent to:

friend class FooTest_BarReturnsZeroOnNull_Test;

This works because each test is its own class as mentioned in the previous answer.

like image 32
Ralfizzle Avatar answered Nov 20 '22 21:11

Ralfizzle


A far better strategy is to not allow friend tests among your unit tests.

Allowing friend tests accessing private members will lead to a code base that is hard to maintain. Tests that break whenever a component's inner implementation details are refactored is not what you want. If extra effort is instead put into getting a design where components can be tested through their public interface, you will get tests that only need updating whenever the public interface of a component is updated.

Tests relying on gtest/gtest_prod.h should be seen as a sign of poor design.

like image 10
Martin G Avatar answered Nov 20 '22 20:11

Martin G