5

The Google Test C++ unit testing framework provides the ability to do parameterised tests. To access the parameter of a given test, the docs tell me to derive a subclass and call GetParam():

class FooTest : public ::testing::TestWithParam<const char*> {
  // You can implement all the usual fixture class members here.
  // To access the test parameter, call GetParam() from class
  // TestWithParam<T>.
};

I cannot find anything more specific than this in either the docs or the source code (inasmuch as I understand it).

Exactly where (or when) can I call GetParam()? I know I can call it in the body of a TEST_P(...) { ... } macro, but what about:

  • In the SetUp() method for FooTest()?
  • In the constructor for FooTest()?
  • In the intialisation list for FooTest()?
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
detly
  • 29,332
  • 18
  • 93
  • 152

1 Answers1

5

Yes, you can. You can assume GetParam() is method of ::testing::TestWithParam base class.

class FooTest : public ::testing::TestWithParam<const char*> {
  std::string name;
  FooTest() : name(GetParam()) {} 
};

With C++11 - you can even just initialize members directly in class:

class FooTest : public ::testing::TestWithParam<const char*> {
  std::string name = GetParam();
};
PiotrNycz
  • 23,099
  • 7
  • 66
  • 112
  • Ooh, nice (the C++11 syntax, I didn't know that). I was confused because while I know I can treat `GetParam()` as a base class method, I wasn't sure *when* whatever `GetParam()` returns is initialised (eg. at construction or in a later call through some GTest magic). – detly Jun 19 '18 at 07:37
  • 1
    You might assume - that base class is already constructed when you start constructing your members - read more here: https://stackoverflow.com/questions/7539282/order-of-calling-constructors-destructors-in-inheritance – PiotrNycz Jun 19 '18 at 07:41