Search code examples
c++c++17googletestenum-class

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


I have an object that has an enum type as a member.

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;
 }
 ...
};

I can have two objects like:

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

and compare the two members like

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

However, if I write a google test that has something like

 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);
    } 

the test fails:

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

What could I be missing?


Solution

  • There's no problem in how you are checking the values for equality:

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

    works exactly as it is expected to do.

    Your problem is most likely in the function you call from class B

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

    This function doesn't do what you expect it to do. You have to investigate there, rather than asking if EXPECT_EQ() works correctly.