我该如何装饰Google Test夹具

时间:2013-02-26 12:00:23

标签: c++ unit-testing googletest

我有一些测试:

class Somefixture: ::testing::Test{};
class Somefixture2: ::testing::Test{};

TEST_F(SomeFixture, SomeName)
{
// ...
}

如何自动将测试链接到两个灯具(装饰)?

TEST_F2(SomeFixture, SomeFixture2, SomeName){}

虽然所需的结果就像我写的那样:

TEST_F(SomeFixture, SomeName)
{
// ...
}
TEST_F(SomeFixture2, SomeName)
{
// ...
}

没有不必要的代码重复

4 个答案:

答案 0 :(得分:1)

有一个小例外(两个测试不能有相同的名称),这应该是正确的解释:

#define TEST_F2(F1, F2, Name)                                  \
template <struct Fixture> struct MyTester##Name : Fixture {    \
  void test##Name();                                           \
};                                                             \
                                                               \
TEST_F(MyTester##Name<F1>, Name##1){ test##Name(); }           \
TEST_F(MyTester##Name<F2>, Name##2){ test##Name(); }           \
                                                               \
template <struct Fixture> void MyTester##Name::test##Name()

这将调用两个测试,每个测试使用MyTester作为夹具,从两个夹具中的一个继承。由于do_test是MyTester的成员,因此它可以访问fixture中的所有继承成员。测试框架将为每个测试创建一个MyTester对象,并将相应的实际夹具创建为基类对象。为了避免与其他测试命名冲突或者对TEST_F2进行不同的调用,我将Name附加到模板名称和测试方法名称。 TEST_F宏调用提供了名称和索引。我没有测试它,因为我没有Google Test,但是许多测试框架中的机制都类似。

答案 1 :(得分:0)

  

如何自动将测试链接到两个灯具(装饰)?

添加公共基类:

class CommonFixture
{
  public:
    // add member variables and initialize them in the constructor
};
class Somefixture1 : ::testing::Test, protected CommonFixture{}
class Somefixture2 : ::testing::Test, protected CommonFixture{}

测试保持不变:

TEST_F(SomeFixture1, SomeName)
{
// ...
}
TEST_F(SomeFixture2, SomeName)
{
// ...
}

现在你有了Somefixture1和Somefixture2的通用夹具。您可以在测试中访问这些常用对象。

答案 2 :(得分:0)

你可以采用BЈовић方式,这似乎很好。
或者需要对测试本身进行少量更改的其他方法可以是一个“超级”类,它将两个实例都作为成员。

class superFuxture
{
public:
    Somefixture1 f1;
    Somefixture2 f2;
}

然后你测试就像那样:

TEST_F(superFuxture, SomeName)
{
    //when you were accessing a member of Somefixture1 you'll now need to do:
    //f1.SomeFixture1Member
}

答案 3 :(得分:0)

Google Test有两种方法可以在不同的上下文中执行相同的测试体:value-parameterized teststyped/type-parameterized tests。不完全是你想要的,但它是它提供的最接近的东西。