如何在Google Test(gtest)中使用夹具成员值运行参数化测试?

尼基塔

我想要实现的是参数化测试TEST_P(MyFixtureClass, DoStuff),通过它我可以测试不同的值。尽管所说的值不应该是常量,就像通常传递给的值一样INSTANTIATE_TEST_CASE_P而且,我想在其他灯具类中使用这些值-理想情况下。

似乎什么都没有,它涵盖了在创建参数化测试时使用字段而不是静态值的问题。遗憾的是官方文档似乎也没有涵盖这一点。


但是为了避免在此问题中引入XY问题,下面是等效的伪代码:

参数化夹具MyFixture

struct MyFixture : OtherFixture, ::testing::WithParamInterface<float>
{
    float a;

    void SetUp() override
    {
        a = GetParam();
    }
};

OtherFixture 看起来像这样:

struct OtherFixture : testing::Test
{
    float a;
    float b;
    float c;

    void SetUp() override
    {
        a = CalculateSomeFloat();
        b = CalculateSomeFloat();
        c = CalculateSomeFloat();
    }
};

测试用例将类似于:

// This here is the key aspect.
// Basically, I do not want to write a bunch of tests for a, b and c.
// Rather, I'd just test all 3 with this one.
TEST_P(MyFixture, DoStuff)
{
    ...bunch of tests
}

最后,我们将实例化参数化测试:

INSTANTIATE_TEST_CASE_P(MyFloatTesting, MyFixture, ::testing::Values(
    OtherFixture::a, OtherFixture::b, OtherFixture::c
));

显然,这OtherFixture::a是不合适的,但是它说明了在继承的夹具类(或与此相关的任何夹具类)中我要引用字段的地方。


那么有什么方法可以用gtest做到这一点吗?我不一定需要使用参数化测试。对于我来说,不必为不同的对象编写相同的测试就可以了。


任何建议,不胜感激!

皮奥特·尼奇(Piotr Nycz)

我认为您需要使用::testing::Combine

并将参数从更改floatstd::tuple<float, float OtherFixture::*>

using OtherFixtureMemberAndValue = std::tuple<float, float OtherFixture::*>;

struct MyFixture : OtherFixture, ::testing::WithParamInterface<OtherFixtureMemberAndValue>
{
    float a = std::get<0>(GetParam());
    auto& memberToTest()
    {
        return this->*std::get<1>(GetParam());
    }


};

要定义参数集,请使用以下方法:

const auto membersToTest = testing::Values(
     &OtherFixture::a, 
     &OtherFixture::b, 
     &OtherFixture::c
);

const auto floatValuesToTest = testing::Values(
    2.1, 
    3.2
    //  ... 
 );

INSTANTIATE_TEST_CASE_P(AllMembers,
                        MyFixture,
                        testing::Combine(floatValuesToTest, membersToTest));

然后,您可以针对以下成员编写通用的测试OtherFixture

TEST_P(MyFixture, test)
{
    ASSERT_EQ(a, memberToTest());
}

我也建议您PrintTofloat OtherFixture::*以下内容写信

void PrintTo(float OtherFixture::*member, std::ostream* os)
{
    if (member == &OtherFixture::a)
        *os << "&OtherFixture::a";
    else if (member == &OtherFixture::b)
        *os << "&OtherFixture::b";
    else if (member == &OtherFixture::c)
        *os << "&OtherFixture::c";
    else
        *os << "&OtherFixture::? = " << member;

}

这样,如果发生故障,您会收到很好的消息:

[失败] AllMembers / MyFixture.test / 5,其中GetParam()=(3.2,&OtherFixture :: c)

与不带PrintTo的讨厌,毫无意义的消息相比:

[FAILED] AllMembers / MyFixture.test / 5,其中GetParam()=(3.2,4字节对象<10-00 00-00>)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章