gtest:检查字符串是否等于两个字符串之一
gtest: check if string is equal to one of two strings
假设我有两个字符串:
std::string s1 = "ab";
std::string s2 = "cd";
我想检查(例如使用 EXPECT_EQ)给定的 std::string str
是否等于 s1
或 s2
.
如果 gtest 的 ASSERT_*
和 EXPECT_*
会 return bool
我可以写
EXPECT_TRUE(EXPECT_EQ(str, s1) || EXPECT_EQ(str, s2));
但不幸的是,他们没有。
试一试:
std::string s1 = "ab";
std::string s2 = "cd";
std::string str = "ab";
EXPECT_TRUE(s1 == str || s2 == str);
在这种情况下 EXPECT_TRUE
有一个问题。在gtest's doc中描述为:
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.
所以建议使用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);
}
如果单元测试失败,它会提供更好的诊断:
[ 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
您可以将上面的消息与 EXPECT_TRUE
的输出进行比较:
Value of: s1 == str || s2 == str
Actual: false
Expected: true
假设我有两个字符串:
std::string s1 = "ab";
std::string s2 = "cd";
我想检查(例如使用 EXPECT_EQ)给定的 std::string str
是否等于 s1
或 s2
.
如果 gtest 的 ASSERT_*
和 EXPECT_*
会 return bool
我可以写
EXPECT_TRUE(EXPECT_EQ(str, s1) || EXPECT_EQ(str, s2));
但不幸的是,他们没有。
试一试:
std::string s1 = "ab";
std::string s2 = "cd";
std::string str = "ab";
EXPECT_TRUE(s1 == str || s2 == str);
在这种情况下 EXPECT_TRUE
有一个问题。在gtest's doc中描述为:
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.
所以建议使用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);
}
如果单元测试失败,它会提供更好的诊断:
[ 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
您可以将上面的消息与 EXPECT_TRUE
的输出进行比较:
Value of: s1 == str || s2 == str
Actual: false
Expected: true