Search code examples
c++unit-testinggoogletest

In my unit test for equality, why does one pointer point to a memory slot rather than the item in memory?


So I am running a unit test:

ASSERT_EQ(mifid_trade_report.contingent_transaction_flag, "CONT");

There is a lot more to the above, but I've cut the rest out as it points to many classes and files.

Here is the error message that I get back when running the test:

/home/.../test_protocol.cpp:2075: Failure
Expected equality of these values:
  mifid_trade_report.contingent_transaction_flag
    Which is: 
  "CONT"
    Which is: 0x563717b6bffe

Two questions:

  1. Am I right in understanding that the above error message is saying mifid_trade_report.contingent_transaction_flag is pointing to CONT, while the CONT is pointing to the memory slot 0x563717b6bffe?

  2. If 1. is right, why is it pointing to a memory slot rather than the object?

I've copied the pattern for other unit tests exactly the same, but the others don't have the same issue.


Solution

  • ASSERT_STREQ(ptr1,ptr2) is what you need. It helps to compare the nul-terminated C style string content. ASSERT_EQ will check for pointer itself since a char* just points to the start of a C string.

    There are other ways. By setting the nul-terminated string into a container with == overloaded. Eg: std::string and std::string_view

    Live Demo

    #include <gtest/gtest.h>
    #include <string_view>
    #include <string>
    #include <fmt/format.h>
    
    TEST(Foo,Bar){
    
        const char* cstring = "foo";
        ASSERT_STREQ(cstring, "foo");
        ASSERT_EQ(std::string(cstring), "foo");
        ASSERT_EQ(std::string_view(cstring), "foo");
    }
    

    Also googletest official documentation does lead you to *_STREQ apis

    Quote:

    EXPECT_EQ

    EXPECT_EQ(val1,val2) ASSERT_EQ(val1,val2)

    Verifies that val1==val2. Does pointer equality on pointers. If used on two C strings, it tests if they are in the same memory location, not if they have the same value. Use EXPECT_STREQ to compare C strings (e.g. const char*) by value.

    When comparing a pointer to NULL, use EXPECT_EQ(ptr, nullptr) instead of EXPECT_EQ(ptr, NULL).