GoogleTest框架 使用总结【一】

xiaoxiao2021-02-28  14

GoogleTest框架 常用命令总结

18.02.24二次整理。(基础部分全部完毕) 18.02.16整理。


闲暇整理,不定期更新~

断言(Assertion)

关于断言(ASSERT_X宏)与预期结果(EXPECT_X)的区别,谷歌官方给出了很好的解释:

ASSERT_ * versions generate fatal failures when they fail, and abort the current function. EXPECT_ * versions generate nonfatal failures, which don’t abort the current function. Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn’t make sense to continue when the assertion in question fails.

翻译成中文,就是断言未通过,断言会中断之后当前测试函数的测试代码(因为之后的测试没有任何意义),而普通的EXPECT会报告出这个错误,仍然会继续执行代码。

ASSERT_X宏列举如下:

条件判断:

ASSERT_TRUE(condition); //条件为真,则通过 ASSERT_FALSE(condition);//条件为假,则通过

值判断:

ASSERT_EQ(val1,val2); //val1 == val2 ASSERT_NE(val1,val2); //val1 != val2 ASSERT_LT(val1,val2); //val1 < val2 ASSERT_LE(val1,val2); //val1 <= val2 ASSERT_GT(val1,val2); //val1 > val2 ASSERT_GE(val1,val2); //val1 >= val2

字符串判断:

ASSERT_STREQ(str1,str2); //两个char* 字符串有同样的内容 ASSERT_STRNE(str1,str2);//两个char* 字符串有不同的内容 ASSERT_STRCASEEQ(str1,str2); //两个char* 字符串有同样的内容,忽略大小写 ASSERT_STRCASENE(str1,str2); //两个char* 字符串有不同的内容,忽略大小写

*STREQ* and *STRNE* also accept wide C strings (wchar_t*). If a comparison of two wide strings fails, their values will be printed as UTF-8 narrow strings.

A NULL pointer and an empty string are considered different.

预期结果(EXPECT)

只需将断言(ASSERT)换成预期(EXPECT)即可,用法跟断言完全一致。 例子:

EXPECT_STREQ(str1,str2) //两个char* 字符串有同样的内容


TEST()与TEST_F()的区别其实并不明显,对于普通的(面向过程)函数测试(不为类的成员函数),直接用TEST即可。 TEST_F主要用于混合式测试(非面向过程)。对于类的测试,Google官方建议我们使用继承于testing::Test这个类来实现我们自己的测试类。官方对于队列的测试类如下:

class QueueTest : public ::testing::Test { protected: virtual void SetUp() { q1_.Enqueue(1); q2_.Enqueue(2); q2_.Enqueue(3); } // virtual void TearDown() {} Queue<int> q0_; Queue<int> q1_; Queue<int> q2_; };

下面为官方给出的测试代码:

TEST_F(QueueTest, IsEmptyInitially) { EXPECT_EQ(0, q0_.size()); } TEST_F(QueueTest, DequeueWorks) { int* n = q0_.Dequeue(); EXPECT_EQ(NULL, n); n = q1_.Dequeue(); ASSERT_TRUE(n != NULL); EXPECT_EQ(1, *n); EXPECT_EQ(0, q1_.size()); delete n; n = q2_.Dequeue(); ASSERT_TRUE(n != NULL); EXPECT_EQ(2, *n); EXPECT_EQ(1, q2_.size()); delete n; }

对于GoogleTest中提及的Invoke,我们可以认为,这个功能等同于开始全部的测试(因为其函数为RUN_ALL_TESTS()),但本函数只能调用一次,不可重复调用。返回值,0为全部成功,1为有没有通过的测试。

文章来源: https://github.com/google/googletest/blob/master/googletest/docs/Primer.md

转载请注明原文地址: https://www.6miu.com/read-2595999.html

最新回复(0)