Passing name and string to parameterized test using google test

Is there a way to pass both type and string to a parameterized test using google test.

I'd like to do:

template <typename T>
class RawTypesTest : public ::testing::TestWithParam<const char * type> {
protected:
  virtual void SetUp() {
       message = type;
  }
}; 

TEST_P(RawTypesTest, Foo) {
  ASSERT_STREQ(message, type);
  ParamType * data = ..;
  ...
}

Thanks in advance

+5
source share
2 answers

Parameterized parameters with parameters will not work for transmitting type information; you can only do this with typed or typed parameterized tests. In both cases, you will have to pack the type and string information into special structures. Here's how to do it with parameterized parameters :

template <typename T> class RawTypesTest : public testing::Test {
 public:
  virtual void SetUp() {
    this->message_ = TypeParam::kStringValue;
  }

 protected:
  const char* const message_;
}

TYPED_TEST_CASE_P(RawTypesTest);

TYPED_TEST_P(RawTypesTest, DoesFoo) {
  ASSERT_STREQ(message, TypeParam::kStringValue);
  TypeParam::Type* data = ...;
}

TYPED_TEST_P(RawTypesTest, DoesBar) { ... }

REGISTER_TYPED_TEST_CASE_P(FooTest, DoesFoo, DoesBar);

And now you need to define the parameter structures and create tests for them:

struct TypeAndString1 {
  typedef Type1 Type;
  static const char* kStringValue = "my string 1";
};
const char* TypeAndString1::kStringValue;

struct TypeAndString2 {
  typedef Type1 Type;
  static const char* kStringValue = "my string 2";
};
const char* TypeAndString2::kStringValue;

typedef testing::Types<TypeAndString1, TypeAndString2> MyTypes;
INSTANTIATE_TYPED_TEST_CASE_P(OneAndTwo, RawTypeTest, MyTypes);

, :

#define MY_PARAM_TYPE(name, type, string) \
  struct name { \
    typedef type Type; \
    static const char kStringValue = string; \
  }; \
  const char* name::kStringValue

:

MY_PARAM_TYPE(TypeAndString1, Type1, "my string 1");
MY_PARAM_TYPE(TypeAndString2, Type2, "my string 2");

, . - , . , .

+9

, TYPED_TEST_P , , . .

#define TSLP(name, value) \
struct Tslp##name \
{ \
   std::string operator()() \
   { \
      return value; \
   } \
}

TSLP(Empty, "");
TSLP(Foo, "foo");
template<class Type, class Param>
class ParamTextFixture : public Type {
    static std::string message() {
        return Param()();
    }
}

, , , ParamTextFixture

typedef ::testing::Types<
    ParamTextFixture<MyClass, TslpEmpty>
    , ParamTextFixture<MyClass, TslpFoo> >
...
0

All Articles