我如何装饰谷歌测试夹具

How can i decorate Google Test fixture

本文关键字:测试 夹具 谷歌 何装饰      更新时间:2023-10-16

我有一些测试:

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

没有不必要的代码重复

除了一个小例外(两个测试不能有相同的名称),这应该在正确的方向:

#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作为从两个fixture之一继承的fixture。由于do_test是MyTester的成员,它可以访问从fixture继承的所有成员。测试框架将为每个测试创建一个MyTester对象,并将相应的实际fixture创建为基类对象。为了避免与其他测试或不同TEST_F2调用之间的命名冲突,我将Name附加到模板名和测试方法名之后。TEST_F宏调用提供了一个名称和索引。我没有测试它,因为我没有Google test,但是许多测试框架的机制都是相似的。

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

通过添加一个公共基类:

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的公共fixture。您可以在测试中访问这些公共对象。

您可以采用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
}

Google Test有两种方法在不同的上下文中执行相同的测试体:值参数化测试或类型/类型参数化测试。不完全是你想要的,但它是最接近它提供的。