谷歌测试:使用现有测试夹具类的参数化测试?

新手上路,请多包涵

我有一个测试夹具类,目前许多测试都在使用它。

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

我想创建一个参数化测试,它还使用 MyFixtureTest 必须提供的所有功能,而无需更改我现有的所有测试。

我怎么做?

我在网上找到了类似的讨论,但没有完全理解他们的答案。

原文由 des4maisons 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 586
2 个回答

问题在于,对于常规测试,您的夹具必须从 testing::Test 派生,而对于参数化测试,它必须从 testing::TestWithParam<> 派生。

为了适应这种情况,您必须修改您的夹具类才能使用您的参数类型

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

这样,您可以在使用创建参数化测试时保持所有现有测试不变

TEST_P(MyParamFixtureTest, MyTestName) { ... }

原文由 VladLosev 发布,翻译遵循 CC BY-SA 2.5 许可协议

这个问题现在在 谷歌测试文档 中得到了 回答(VladLosev 的回答在技术上是正确的,但可能需要做更多的工作)

具体来说,当您想将参数添加到预先存在的夹具类时,您可以这样做

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

TEST_P(MyParamFixtureTest, MyTestName) { ... }

原文由 mabraham 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题