GTEST-限定名称未在“:”标记之前命名类

时间:2018-12-12 10:46:09

标签: c++ googletest gmock

这是示例代码:

#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是否必须与灯具位于同一名称空间中?

1 个答案:

答案 0 :(得分:1)

摘自TEST_F文档:

  

第一个参数是测试治具类的名称,它也是测试用例名称的两倍。

第一个参数用作测试类名称的一部分,因此将复合标识符放在其中会使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()
{

}

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

如果要使用来自其他名称空间的灯具,则需要将其名称带入当前名称空间,然后在宏中使用非限定名称:

using A::B::MyFixture;

TEST_F(MyFixture, Test1)
{
…