本文开始从googletest提供的sample案例分析如何使用单元测试,
代码路径在googletest/googletest/samples/sample1.unittest.cc
本文件主要介绍EXPECT*相关宏使用
EXPECT_EQ 判断是否相等
EXPECT_TRUE 是否为True
EXPECT_FALSE 是否为False
TEST(FactorialTest, Negative) {
// This test is named "Negative", and belongs to the "FactorialTest"
// test case.
EXPECT_EQ(1, Factorial(-5));
EXPECT_EQ(1, Factorial(-1));
EXPECT_GT(Factorial(-10), 0);
//
//
// EXPECT_EQ(expected, actual) is the same as
//
// EXPECT_TRUE((expected) == (actual))
//
// except that it will print both the expected value and the actual
// value when the assertion fails. This is very helpful for
// debugging. Therefore in this case EXPECT_EQ is preferred.
//
// On the other hand, EXPECT_TRUE accepts any Boolean expression,
// and is thus more general.
//
//
}
下面介绍sample2_unittest.cc文件
这里测试MyString类,
EXPECT_STREQ(nullptr, s.c_string()); //这里的STREQ是判断字符串内容,s为空类比较要使用nullptr
TEST(MyString, DefaultConstructor) {
const MyString s;
// Asserts that s.c_string() returns NULL.
//
//
//
// If we write NULL instead of
//
// static_cast(NULL)
//
// in this assertion, it will generate a warning on gcc 3.4. The
// reason is that EXPECT_EQ needs to know the types of its
// arguments in order to print them when it fails. Since NULL is
// #defined as 0, the compiler will use the formatter function for
// int to print it. However, gcc thinks that NULL should be used as
// a pointer, not an int, and therefore complains.
//
// The root of the problem is C++'s lack of distinction between the
// integer number 0 and the null pointer constant. Unfortunately,
// we have to live with this fact.
//
//
EXPECT_STREQ(nullptr, s.c_string());
EXPECT_EQ(0u, s.Length());
}