user1919249
user1919249

Reputation: 377

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?

Upvotes: 5

Views: 5934

Answers (1)

user1919249
user1919249

Reputation: 377

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();
    }
}

Upvotes: 4

Related Questions