使用FRIEND_TEST测试另一个命名空间中类的私有函数



我试图使用GTest的FRIEND_TEST()宏来启用从另一个命名空间的一些私有函数的测试。然而,我不能通过一些错误,虽然我一定是错过了一些简单的。

我有Tests.cpp,我想测试MyClass的私有功能:

namespace a::b::tests 
{
class MyTests : public ::testing::Test { ... };
TEST_F(MyTests, Test1)
{
// Test private functions of MyClass instance from MyClass.cpp
...
}
}

MyClass.h中,在MyClass.cpp中实现,我有:

namespace a::b
{
class MyTests_Test1_Test; // Forward declaration.
class MyClass
{
private:
FRIEND_TEST(a::b::tests::MyTests, Test1);   
...
};
}

但是,编译时出现'a::b::tests' has not been declarederror: friend declaration does not name a class or function错误。

如果我尝试通过在MyClass.h中添加using a::b::tests;来前声明命名空间,错误仍然存在。

我如何才能正确地使MyTests成为MyClass的朋友类?

您需要添加前向声明对于a::b::tests::MyTests,因为你已经在源文件Tests.cpp中实现了它,这与头文件MyClass.h不同,在你写FRIEND_TEST(a::b::tests::MyTests, Test1);的时候,编译器不知道有一个类a::b::tests::MyTests

所以把这个添加到你的头文件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);   
...
};
}

原来我必须做这样的前向声明,在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);   
...
};
}

最新更新