如何用googletest检查两个枚举类元素的相等性?

问题描述 投票:0回答:2

我有一个枚举类型作为成员的对象。

enum class Color { Blue=1, Green=2, Red=3}; 
struct A {
    int f;
    Color color;
    A(int x, Color c) : f(x), color(c) {}
};

struct B{
     ...
     std::unique_ptr<A> makeObject(size_t index, Color col) {
     ... // other unrelated parsing and verification code
     auto obj = std::make_unique<A>(index, col);
     return obj;
 }
 ...
};

我可以有两个对象,如:

B b;
auto first = b.makeObject(2, Color::Blue);
auto second = std::make_unique<A>(2, Color::Blue);

并比较两个成员

 if (first->color == second->color) {...}

但是,如果我写一个类似的谷歌测试

 TEST(StuffTest, makeObjectTest) {
        B stuffObject;
        auto retStuff = stuffObject.makeObject(1, Color::Red);

        auto testStuff = std::make_unique<A>(1, Color::Red);

        EXPECT_EQ(retStuff->f, testStuff->f);
        EXPECT_EQ(retStuff->color, testStuff->color);
    } 

测试失败:

Expected equality of these values:
retStuff->color
Which is: 4-byte object <62-01 00-00>
testStuff->color
Which is: 4-byte object <11-01 00-00>
[  FAILED  ]... 

我能错过什么?

c++ c++17 googletest enum-class
2个回答
3
投票

如何检查相等的值是没有问题的:

EXPECT_EQ(retStuff->color, testStuff->color);

完全按照预期的方式工作。

您的问题最有可能发生在您从班级B调用的函数中

auto retStuff = stuffObject.makeObject(1, Color::Red);

此功能无法按预期执行。你必须在那里进行调查,而不是询问EXPECT_EQ()是否正常工作。


0
投票

你在googletest中检查两个枚举类的相等性的方法是使用EXPECT_EQ()

该测试通过:

TEST(StuffTest, makeObjectTest) {
    auto retStuff = std::make_unique<A>(1, Color::Red);
    auto testStuff = std::make_unique<A>(1, Color::Red);

    EXPECT_EQ(retStuff->f, testStuff->f);
    EXPECT_EQ(retStuff->color, testStuff->color);
}

一些输出(clang,macOS):

[----------] 1 test from StuffTest
[ RUN      ] StuffTest.makeObjectTest
[       OK ] StuffTest.makeObjectTest (0 ms)
[----------] 1 test from StuffTest (0 ms total)

问题必须在stuffObject.makeObject(1, Color::Red)电话中,正如其他人所指出的那样。如果您需要更多帮助,您必须展示这个makeObject功能正在做什么。

© www.soinside.com 2019 - 2024. All rights reserved.