GTest类型测试 - 使用

时间:2017-09-22 21:52:17

标签: c++ googletest

我想在下面的'DoesBlah'测试中使用基类中的'MyType'。

#include <gtest/gtest.h>

template <typename T>
struct MemberVariable
{
    T m_t;
};

struct Base : public ::testing::Test
{
    template <typename MemberType>
    using MyType = MemberVariable<MemberType>;
};

template <typename DerivedType>
struct Derived : public Base
{
};

typedef ::testing::Types<int, char> MyTypes;
TYPED_TEST_CASE(Derived, MyTypes);

TYPED_TEST(Derived, DoesBlah)
{
    MyType<TypeParam> test;
    test.m_t = (TypeParam)1;
    ASSERT_EQ(test.m_t, 1);
}

但是,我收到以下编译错误:

gti/specific/level/Test.t.cpp: In member function 'virtual void Derived_DoesBlah_Test<gtest_TypeParam_>::TestBody()':
gti/specific/level/Test.t.cpp:25:5: error: 'MyType' was not declared in this scope
     MyType<TypeParam> test;

我尝试使用TestFixture :: MyType,typename TestFixture :: MyType,但两者都不起作用。

我怎样才能让Derived认识到有一种叫做'MyType'的东西?

1 个答案:

答案 0 :(得分:2)

通过一些简化,宏TYPED_TEST(Derived, DoesBlah)扩展为:

template <typename TypeParam>
class Derived_DoesBlah_Test : public Derived<TypeParam>
{
private:
    typedef Derived<TypeParam> TestFixture;
    virtual void TestBody();
};
template <typename TypeParam>
void Derived_DoesBlah_Test<TypeParam>::TestBody()

因此,后面的{}块是从Derived<TypeParam>派生的模板类成员的函数定义。 typedef的{​​{1}}可用,但它取决于模板参数TestFixture,因此它被视为依赖类型。此外,您还希望访问该依赖类型的模板成员。因此,您需要TypeParamtypename个关键字:

template

有关相关类型的更多信息,并在声明和表达式中使用{ typename TestFixture::template MyType<TypeParam> test; test.m_t = (TypeParam)1; ASSERT_EQ(test.m_t, 1); } typename关键字,请参阅this SO question