Google Test:使用现有测试夹具类的参数化测试?

时间:2010-06-30 18:40:09

标签: c++ unit-testing googletest

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

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

我想创建一个参数化测试,该测试也使用MyFixtureTest提供的所有测试,而无需更改我现有的所有测试。

我该怎么做?

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

3 个答案:

答案 0 :(得分:36)

现在Google Test documentation回答了这个问题(VladLosev的answer在技术上是正确的,但可能稍微多一些工作)

具体来说,当您想要将参数添加到预先存在的灯具类时,您可以执行

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

TEST_P(MyParamFixtureTest, MyTestName) { ... }

答案 1 :(得分:20)

问题在于,对于常规测试,您的夹具必须来自于测试:: Test和参数化测试,它必须来自test :: TestWithParam&lt;&gt;。

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

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

答案 2 :(得分:0)

如果您创建一个派生自这个常用夹具的新夹具,而不是在该派生类上创建参数化测试 - 这会对您有所帮助并解决您的问题吗?

来自Google Test wiki page: “在Google Test中,您可以通过将共享逻辑放在基础测试夹具中来共享测试用例中的夹具,然后从该基础派生一个单独的夹具,用于每个想要使用这种通用逻辑的测试用例。”

相关问题