在程序中,断言结果就是一个bool值。用过c++的都知道assert。它可以对单一表达式或者二元表达式进行判断,在c++的通常应用中,它是一个宏。在gtest中它的表现形式也是一种宏,它主要有两大类:
在gtest中有以下几种主要的断言形式:
ASSERT_TRUE(condition);
EXPECT_TRUE(condition);
ASSERT_FALSE(condition);
EXPECT_FALSE(condition);
这个一看字面意思就明白,不作解释了。
ASSERT_EQ(expected, actual);
EXPECT_EQ(expected, actual);
ASSERT_NE(val1, val2); EXPECT_NE(val1, val2);
ASSERT_LT(val1, val2); EXPECT_LT(val1, val2);
ASSERT_LE(val1, val2); EXPECT_LE(val1, val2);
ASSERT_GT(val1, val2); EXPECT_GT(val1, val2);
ASSERT_GE(val1, val2); EXPECT_GE(val1, val2);
这个如果学过汇编语言的可能一下子就明白了,其实后面的字符串就是比较的缩写,比如EQ是常见的等于;GT是大于,其它都类似。
ASSERT_STREQ(expected_str, actual_str);
EXPECT_STREQ(expected_str, actual_str);
ASSERT_STRNE(str1, str2);
EXPECT_STRNE(str1, str2);
ASSERT_STRCASEEQ(expected_str, actual_str);
EXPECT_STRCASEEQ(expected_str, actual_str);
ASSERT_STRCASENE(str1, str2);
EXPECT_STRCASENE(str1, str2);
其实和数值断言类似,只不过在字符串中可能存在大小写,所以要对这个进行处理一下。
SUCCEED();FAIL(); ADD_FAILURE();
ASSERT_THROW(statement, exception_type);
EXPECT_THROW(statement, exception_type);
ASSERT_ANY_THROW(statement);
EXPECT_ANY_THROW(statement);
ASSERT_NO_THROW(statement);
EXPECT_NO_THROW(statement);
ASSERT_PRED1(pred1, val1);
EXPECT_PRED1(pred1, val1);
ASSERT_PRED2(pred2, val1, val2);
EXPECT_PRED2(pred2, val1, val2);
ASSERT_PRED_FORMAT1(pred_format1, val1);
EXPECT_PRED_FORMAT1(pred_format1, val1);
ASSERT_PRED_FORMAT2(pred_format2, val1, val2);
EXPECT_PRED_FORMAT2(pred_format2, val1, val2);
这个要是搞过《离散数学》的可能就比较清楚,不过看过STL的源码的应该也好理解,其实就是有一个处理函数罢了。如果自己认为有更好的解决方式还可以自定义谓词。
ASSERT_FLOAT_EQ(expected, actual);
EXPECT_FLOAT_EQ(expected, actual);
ASSERT_DOUBLE_EQ(expected, actual);
EXPECT_DOUBLE_EQ(expected, actual);
ASSERT_NEAR(val1, val2, abs_error);
EXPECT_NEAR(val1, val2, abs_error);
这个没啥可更多解释的。
ASSERT_HRESULT_SUCCEEDED(expression);
EXPECT_HRESULT_SUCCEEDED(expression);
ASSERT_HRESULT_FAILED(expression);
EXPECT_HRESULT_FAILED(expression);
这个有点类似于早期模板中的编译检查或者c++20后的概念Concepts,就是作一个类型的检测。
//字符串断言
TEST(StringCmpTest, Demo)
{
char* pStr = "mytest";
wchar_t* wpStr = L"mytest";
std::string str = "mystring";
std::wstring wstr = L"mystring";
EXPECT_STREQ("mytest", pStr );
EXPECT_STREQ(L"mytest", wpStr );
EXPECT_STRNE("notest", pStr );
EXPECT_STRNE(L"notest", wpStr );
EXPECT_STRCASEEQ("myTest",pStr);
EXPECT_STREQ("mytest",str.c_str());
EXPECT_STREQ(L"mytest",wstr.c_str());
}
//异常断言
int CheckData(int a, int b)
{
if (a == 0 || b == 0)
{
throw "error zero";
}
int c = a % b;
if (c == 0)
{
return b;
}
return CheckData(b, c);
}
TEST(CheckDataTest, HandleZeroInput)
{
EXPECT_ANY_THROW(CheckData(1, 0));
EXPECT_THROW(CheckData(0, 5), char*);
}
//谓词断言
bool CompareV(int m, int n)
{
if (m > n)
{
return true;
}
else
{
return false;
}
}
TEST(PAssertionTest,MyTest)
{
int m = 15, n = 3;
EXPECT_PRED2(CompareV, m, n);
}