des4maisons des4maisons - 1 year ago 90
C++ Question

Google Test: Parameterized tests which use an existing test fixture class?

I have a test fixture class which is currently used by many tests.

#include <gtest/gtest.h>
class MyFixtureTest : public ::testing::Test {
void SetUp() { ... }
};


I would like to create a parameterized test which also uses all that MyFixtureTest has to offer, without needing to change all my existing tests.

How do I do that?

I have found similar discussions on the web, but have not fully understood their answers.

Answer Source

The problem is that for regular tests your fixture has to be derived from testing::Test and for parameterized tests, it has to be derived from testing::TestWithParam<>.

In order to accommodate that, you'll have to modify your fixture class in order to work with your parameter type

template <class T> class MyFixtureBase : public T {
  void SetUp() { ... };
  // Put the rest of your original MyFixtureTest here.
};

// This will work with your non-parameterized tests.
class MyFixtureTest : public MyFixtureBase<testing::Test> {};

// This will be the fixture for all your parameterized tests.
// Just substitute the actual type of your parameters for MyParameterType.
class MyParamFixtureTest : public MyFixtureBase<
    testing::TestWithParam<MyParameterType> > {};

This way you can keep all your existing tests intact while creating parameterized tests using

TEST_P(MyParamFixtureTest, MyTestName) { ... }