FAQ / QTE (Quality Town for Embedded Grade)
【QTE21】Test Creation Issues
QTE21_06 : Google Test
【question】
How can I access private member variables of the class under test from the test driver?
【Answer】
As a way to test private member variables of the class under test、
@ How to declare a test fixture class as a friend class
A How to declare a test driver function as a FRIEND function
There are two ways to do this.
@ How to declare a test fixture class as a friend class
Declare the test fixture class as a friend class of the class under test so that member functions of the test fixture class can access
private variables of the class under test. Next, define a Getter function for the private variable in the test fixture class.
The test driver function uses the Getter function to access private variables.

An example will be used to illustrate.
Create a function to test the value of the num_ member of the Sample class to be tested.
Declare the SampleTest class as a friend class of the Sample class so that the SampleTest class can access the num_ members of the Sample class.
// Header to be tested (sample.h)
class Sample {
friend class SampleTest;
public:
// omission
private:
int num_;
};
Define a get_num member function in the test fixture class that accesses the num_ member of the Sample class.
The test driver function calls the get_num function of the test fixture class to obtain the value of the num_ member.
// Test Driver Source(sampleTest.cpp)
class SampleTest : public ::testing::Test {
protected:
int get_num(const Sample& sample) { return sample.num_; }
};
TEST_F(SampleTest, test1)
{
Sample obj;
// omission
EXPECT_EQ(2, get_num(obj));
}
A How to declare a test function as a friend function
Declare the test function of the test driver as a friend function of the class under test; use the FRIEND_TEST macro to define it as a friend function.
Example) Declare the TEST(SampleTest, test1) function as a friend function using the FRIEND_TEST macro as follow
#include "gtest/gtest.h"
class Sample {
FRIEND_TEST(SampleTest, test1);
// omission
};
Getting Started Guide to Google Test Documentat(
http://opencv.jp/googletestdocs/primer.html#primer-test-fixtures)
describes the test fixture.
For more information on test fixtures, please see there.
Also, for more information on the two methods, see "Private Class Members" in the "Testing Private Code" section of the Advanced Guide to Google Test documentation.
(
http://opencv.jp/googletestdocs/advancedguide.html#adv-private-class-members)に記載されています。
Please refer to that as well.
Search for related support information.