Pages

C-string comparison

For checking C++ strings while using Google Test we can use the normal binary comparison ASSERT / EXPECT macros. We can do that because std::string properly redefines the comparison operators.

But if we talk about c-string we can't rely on those macros. As we well know, checking s == t, when s and t are two bare pointers to character, performs a check on the pointers and not to the actual strings of characters.

To check two c-strings for content equality we can use ASSERT_STREQ and EXPECT_STREQ; to enforce their difference we have ASSERT_STRNE and EXPECT_STRNE. Then we have the "ignore case" versions: ASSERT_STRCASEEQ / EXPECT_STRCASEEQ and ASSERT_STRCASENE / EXPECT_STRCASENE.

An example to clarify the matter:

TEST(TestCString, CString) {
const char* const expected = "A string";
const char* const actual = "Another string";
const char* const actual2 = "A string";
const char* const actual3 = "a string";

EXPECT_STREQ(expected, actual);
EXPECT_STRNE(expected, actual2);
EXPECT_STRCASEEQ(expected, actual3); // 1.
EXPECT_STRCASENE(expected, actual3);
}

1. this is the only test that actually succeed, since the two strings differ only in the case of the first letter. The other three test fail, as reported by Guitar:

(...)\test.cpp(56): error: Value of: actual
Actual: "Another string"
Expected: expected
Which is: "A string"
(...)\test.cpp(57): error: Expected: (expected) != (actual2),
actual: "A string" vs "A string"
(...)\test.cpp(59): error: Expected: (expected) != (actual3) (ignoring case),
actual: "A string" vs "a string"

No comments:

Post a Comment