Search code examples
c++unit-testinggoogletestprivate-members

Accessing private members with GoogleTest


I'm having trouble friending to access private members. Here is my code.

#pragma once
#ifndef TEST_FRIENDS
#define TEST_FRIENDS
#endif

namespace LibToTestNamespace
{
    class LibToTest
    {
    public:
        double Add(double, double);

    private:
        TEST_FRIENDS;
        int GetMyInt();
        int mInt;
    };
}

and

#include "UnitTests.h"
#define TEST_FRIENDS \
    friend class TestCustomUnitTest_hello_Test;
#include "LibToTest.h"

TEST(TestCustomUnitTest, hello)
{
    LibToTestNamespace::LibToTest ltt;
    ltt.mInt = 5;
    ltt.GetMyInt();
}

I get errors "cannot access private member declared in class". I'm thinking the lib gets built first so TEST_FRIENDS isn't getting replaced correctly? But if the unit test depends on the library, it will always get built first right?


Solution

  • I got this to work by wrapping my Unit test class in the same namespace that my production class existed in.

    namespace LibToTestNamespace
    {
        TEST(TestCustomUnitTest, hello)
        {
            LibToTest ltt;
            ltt.mInt = 5;
            ltt.GetMyInt();
        }
    }