【问题标题】:How to get gtest TYPED_TEST parameter type如何获取 gtest TYPED_TEST 参数类型
【发布时间】:2017-07-21 09:28:11
【问题描述】:

我有一些在 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;
} 

在成员函数'virtual void MyTest_MyTestName_Test::TestBody()':error: 'MyParamType' 未在此范围内声明 MyParamType 参数;

改为:

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

代码可以编译,但是看起来很丑。

有没有简单/好方法从TYPED_TEST 获取模板参数类型?

【问题讨论】:

  • 我意识到 gtest 正是为此定义了TypeParam

标签: c++ googletest


【解决方案1】:

答案隐藏在文档中:

#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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
相关资源
最近更新 更多