如何获取gtest TYPED_TEST参数类型

时间:2017-07-21 09:28:12

标签: c++ googletest

我在Windows上编写了一些单元测试(Visual Studio 2017),我需要在Linux上移植它们(GCC 4.9.2 - 我已经坚持使用这个版本......)。我已经为我的问题提供了一个简单的例子,它在Windows上编译得很好(我不认为它应该编译,因为MyParamType是来自e模板基类的依赖类型)并且没有'在Linux上编译。

示例:

#include <gtest/gtest.h>

template<typename T>
struct MyTest : public testing::Test
{
    using MyParamType = T;
};

using MyTypes = testing::Types<int, float>;
TYPED_TEST_CASE(MyTest, MyTypes);

TYPED_TEST(MyTest, MyTestName)
{
    MyParamType param;
} 
  

在成员函数'虚拟空虚中   MyTest_MyTestName_Test :: TestBody()':错误:未在此范围内声明'MyParamType'   MyParamType参数;

改为:

TYPED_TEST(MyTest, MyTestName)
{
    typename MyTest<gtest_TypeParam_>::MyParamType param;
}

代码编译,但看起来很难看。

是否有一种简单/好的方法可以从TYPED_TEST获取模板参数类型?

1 个答案:

答案 0 :(得分:5)

答案隐藏在文档中:

#include <gtest/gtest.h>

template<typename T>
struct MyTest : public testing::Test
{
    using MyParamType = T;
};

using MyTypes = testing::Types<int, float>;
TYPED_TEST_CASE(MyTest, MyTypes);

TYPED_TEST(MyTest, MyTestName)
{
    // To refer to typedefs in the fixture, add the 'typename TestFixture::'
    // prefix.  The 'typename' is required to satisfy the compiler.

    using MyParamType  = typename TestFixture::MyParamType;
}

https://github.com/google/googletest/blob/master/googletest/docs/advanced.md