I'm trying to use GTest's FRIEND_TEST()
macro to enable testing of some private functions from another namespace. However, I can't get past some errors, though I must be missing something simple.
I have Tests.cpp
where I would like to test private functionality of MyClass
:
namespace a::b::tests
{
class MyTests : public ::testing::Test { ... };
TEST_F(MyTests, Test1)
{
// Test private functions of MyClass instance from MyClass.cpp
...
}
}
In MyClass.h
, implemented in MyClass.cpp
, I have:
namespace a::b
{
class MyTests_Test1_Test; // Forward declaration.
class MyClass
{
private:
FRIEND_TEST(a::b::tests::MyTests, Test1);
...
};
}
However, this fails with compile-time errors 'a::b::tests' has not been declared
and error: friend declaration does not name a class or function
.
If I try to forward-declare the namespace by adding using a::b::tests;
in MyClass.h
, the error remains.
How can I properly make MyTests
a friend class of MyClass
here?
CodePudding user response:
You need to add a forward declaration for a::b::tests::MyTests
because you've implemented it in a source file Tests.cpp
which is different from the header file MyClass.h
and at the point where you've written FRIEND_TEST(a::b::tests::MyTests, Test1);
the compiler doesn't know that there is a class a::b::tests::MyTests
.
So to solve this add this in your header file MyClass.h
:
MyClass.h
namespace a::b::tests
{
//-------------v-------------->note only a declaration and not a definition
class MyTests;//added this forward declaration
}
////////////////////////////
//now we can write the below code exactly as before since we have a forward declaration for a::b::tests::MyTests
namespace a::b
{
class MyTests_Test1_Test;
class MyClass
{
private:
FRIEND_TEST(a::b::tests::MyTests, Test1);
...
};
}
CodePudding user response:
Turns out I had to do forward declarations like this, in MyClass.h
:
namespace a::b::tests
{
class MyTests;
class MyTests_Test1_Test;
}
namespace a::b
{
class MyClass
{
private:
FRIEND_TEST(a::b::tests::MyTests, Test1);
...
};
}