Mircea Ispas
Mircea Ispas

Reputation: 20780

How to get gtest TYPED_TEST parameter type

I have some unit tests written on Windows (Visual Studio 2017) and I need to port them on Linux (GCC 4.9.2 - I'm stuck with this version...). I've come with a simple example for my problem which compiles fine on Windows (I don't think it should compile as MyParamType is a dependent type from e template base class) and doesn't compile on Linux.

Example:

#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;
} 

In member function ‘virtual void MyTest_MyTestName_Test::TestBody()’:error: ‘MyParamType’ was not declared in this scope MyParamType param;

By changing to:

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

The code compiles, but it looks very ugly.

Is there an easy/nice way to get the template parameter type from a TYPED_TEST?

Upvotes: 8

Views: 12462

Answers (1)

Richard Hodges
Richard Hodges

Reputation: 69882

The answer is hidden in the docs:

#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

Upvotes: 11

Related Questions