gtest: check if string is equal to one of two strings
Asked Answered
L

3

11

Consider that I have two strings:

std::string s1 = "ab"; 
std::string s2 = "cd";

and I want to check (e.g. using EXPECT_EQ) if some given std::string str is equal either to s1 or s2.

If gtest's ASSERT_* and EXPECT_* would return bool I could have written

EXPECT_TRUE(EXPECT_EQ(str, s1) || EXPECT_EQ(str, s2));

but, unfortunately, they don't.

Lithophyte answered 7/8, 2018 at 16:30 Comment(5)
What about assigning to bool variable and expect the variable valueRankin
EXPECT_TRUE(str==s1 || str==s2) ?Ulcer
@ikanab OK, it will work, thanks. I just wanted to know if there is a gtest macro for such test.Lithophyte
Of course, you can write your own macro.Windbound
It's fortunate that they don't because your test would fail whenever str didn't equal s1.Wahkuna
H
14

There is one problem with EXPECT_TRUE in this case. In gtest's doc it is described as:

sometimes a user has to use EXPECT_TRUE() to check a complex expression, for lack of a better macro. This has the problem of not showing you the values of the parts of the expression, making it hard to understand what went wrong.

So it is suggested to use EXPECT_PRED:

TEST(CompareStr, Test1) {
  std::string s1 = "ab";
  std::string s2 = "cd";
  std::string str;
  EXPECT_PRED3([](auto str, auto s1, auto s2) {
    return str == s1 || str == s2;}, str, s1, s2);
}

It gives a bit better diagnostic if a unittest fails:

[ RUN      ] CompareStr.Test1
Test.cpp:5: Failure
[](auto str, auto s1, auto s2) { return str == s1 || str == s2;}(str, s1, s2) evaluates to false, where
str evaluates to 
s1 evaluates to ab
s2 evaluates to cd

You can compare the message above with the output from EXPECT_TRUE:

Value of: s1 == str || s2 == str
  Actual: false
Expected: true
Headmaster answered 7/8, 2018 at 17:0 Comment(1)
Thanks for putting me into the right direction, but even so, your sample is wrong: You have to use EXPECT_PRED2 only with s1 and s2 of course. Just try your sample with s1 = "ab" and s2 = "ab". Test will fail since "str" is always an empty string!Albumose
S
9

Try it:

std::string s1 = "ab";
std::string s2 = "cd";
std::string str = "ab";

EXPECT_TRUE(s1 == str || s2 == str);
Sixtyfour answered 7/8, 2018 at 16:37 Comment(1)
I am in the situation that I have used as described and now I don't know why test is failing on server build but locally the tests succeeds. See bellow for a better solution.Albumose
B
3

Use ASSERT_STREQ or EXPECT_STREQ instead of EXPECT_EQ for comparing strings. Therefore, you need to convert the std::string to a C string.

For your example:

std::string s1 = "ab";
std::string s2 = "cd";
ASSERT_STREQ(s1.c_str(), s2.c_str());

Reference: https://github.com/google/googletest/blob/main/docs/reference/assertions.md#expect_streq-expect_streq

Benyamin answered 6/9, 2023 at 6:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.