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

How do I check equality of two enum class elements with googletest?

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

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

但是,如果我编写一个 google 测试,其中包含

 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  ]... 

我可能遗漏了什么?

您检查值是否相等的方式没有问题:

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

完全按照预期工作。

您的问题很可能出在您从 class B

调用的函数中
auto retStuff = stuffObject.makeObject(1, Color::Red);

此功能未达到您的预期。您必须在那里进行调查,而不是询问 EXPECT_EQ() 是否正常工作。

检查 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 函数的作用。