GoogleTest框架 使用總結【一】

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

發佈了69 篇原創文章 · 獲贊 39 · 訪問量 17萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章