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

荒凉一梦 提交于 2019-11-30 01:49:58

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) { ... }
mabraham

This question is now answered in the Google Test documentation (the answer from VladLosev is technically correct, but perhaps slightly more work)

Specifically, when you want to add parameters to a pre-existing fixture class, you can do

class MyFixtureTest : public ::testing::Test {
  ...
};
class MyParamFixtureTest : public MyFixtureTest,
                           public ::testing::WithParamInterface<MyParameterType> {
  ...
};

TEST_P(MyParamFixtureTest, MyTestName) { ... }

If you create a new fixture that is derived from this common one and than create your parameterized tests on that derived class - would that help you and solve your problem?

From Google Test wiki page: "In Google Test, you share a fixture among test cases by putting the shared logic in a base test fixture, then deriving from that base a separate fixture for each test case that wants to use this common logic."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!