c++ - GTEST - 限定名称未在 ':' 标记之前命名类

标签 c++ googletest googlemock

这里是一个示例代码:

#include <gtest/gtest.h>
#include <gmock/gmock.h>

namespace A { namespace B {

struct MyFixture: public ::testing::Test
{
};

}}

TEST_F(A::B::MyFixture, Test1)
{

}

int main(int argc, char** argv)
{
    ::testing::InitGoogleMock(&argc, argv);
    return RUN_ALL_TESTS();
}

我收到以下错误:

gtest-internal.h:1255: error: qualified name does not name a class before ‘:’ token
gtest.h:2305: in expansion of macro ‘GTEST_TEST_’
main.cpp:29: in expansion of macro ‘TEST_F’
gtest-internal.h:1255: error: expected ‘{’ before ‘:’ token
gtest.h:2305: in expansion of macro ‘GTEST_TEST_’
main.cpp:29: in expansion of macro ‘TEST_F’
gtest-internal.h:1255: error: expected unqualified-id before ‘:’ token
gtest.h:2305: in expansion of macro ‘GTEST_TEST_’
main.cpp:29: in expansion of macro ‘TEST_F’

如何解决这个问题? TEST_F 是否必须与固定装置位于同一命名空间中?

最佳答案

来自 TEST_F 文档:

The first parameter is the name of the test fixture class, which also doubles as the test case name.

第一个参数用作测试类名称的一部分,因此将复合标识符放在那里会使 TEST_F(A::B::MyFixture, Test1) 宏扩展为无效代码:

class A::B::MyFixture_Test1_Test: public A::B::MyFixture
{
    public: A::B::MyFixture_Test1_Test()
    {
    }
    private: virtual void TestBody();

    static ::testing::TestInfo* const test_info_;

    A::B::MyFixture_Test1_Test(A::B::MyFixture_Test1_Test const &) = delete;

    void operator=(A::B::MyFixture_Test1_Test const &) = delete;
};

::testing::TestInfo* const A::B::MyFixture_Test1_Test::test_info_ = ::testing::internal::MakeAndRegisterTestInfo
(
    "A::B::MyFixture"
,   "Test1"
,   nullptr
,   nullptr
,   ::testing::internal::CodeLocation
    (
        "d:\\projects\\googletest-master\\googletest\\src\\gtest-all.cc", 60
    )
,   (::testing::internal::GetTypeId<A::B::MyFixture>())
,   A::B::MyFixture::SetUpTestCase
,   A::B::MyFixture::TearDownTestCase
,   new ::testing::internal::TestFactoryImpl<A::B::MyFixture_Test1_Test>
);

void A::B::MyFixture_Test1_Test::TestBody()
{

}

这是基于宏的单元测试框架的众多缺点之一。

如果您想使用来自不同 namespace 的固定装置,您需要将其名称带入当前 namespace ,然后在宏中使用非限定名称:

using A::B::MyFixture;

TEST_F(MyFixture, Test1)
{
… 

关于c++ - GTEST - 限定名称未在 ':' 标记之前命名类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53741282/

相关文章:

python - PyObject_CallObject 在 bytearray 方法上失败

c++ - 我应该使用什么结构来模拟用于桌面测试的嵌入式系统类?

c++ - GMock : How to return a fuction pointer defined by an EXPECT_CALL()

c++ - Google Mock : passing pointer to mock object, 但方法调用仍在调用真实方法

c++ - 在c中生成解析树

c++ - 如何从std::thread返回值

c++ - std::string(char* char_array) 是如何实现的?

unit-testing - 使用谷歌测试测试崩溃

c++ - 为什么 Google 测试在一台机器上通过但在另一台机器上失败?

c++ - Google Test Main 没有声明 main