gtest初識

gtest初識總結

本文以結合gtest github內容進行學習gtest。

gtest github地址

gtest編譯

g++ xx.cpp xx.h -lgtest -lpthread -o main

gtest編寫

創建測試的一個簡易的步驟:

1.使用TEST()宏來定義和命名測試函數,這些是不返回值的普通C ++函數。
2.在此函數中,與要包含的任何有效C ++語句一起使用各種googletest斷言來檢查值.(ASSERT_()、EXPECT_())
3.測試的結果由斷言決定; 如果測試中的任何斷言失敗(無論是致命的還是非致命的),或者測試崩潰,整個測試都會失敗。否則,它會成功。

TEST()第一個參數是測試用例的名稱,第二個參數是測試用例中的測試名稱(有效的C++標識符,不應包含下劃線)。
googletest按照測試用例對測試結果進行分組。

例子Demo

文件 描述
sample1.cc 待測試代碼包含兩個函數:
1:Factorial(int n) 階乘函數。
2:IsPrime(int n) 是否是質數
sample1.h 待測試代碼頭文件
simple1_unittest.cc 測試用例代碼文件
main.cpp 程序入口文件

代碼如下:

sample1.h

#ifndef GTEST_SAMPLES_SAMPLE1_H_
#define GTEST_SAMPLES_SAMPLE1_H_

// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
int Factorial(int n);

// Returns true iff n is a prime number.
bool IsPrime(int n);

#endif  // GTEST_SAMPLES_SAMPLE1_H_

sample.cc

#include "sample1.h"

// Returns n! (the factorial of n).  For negative n, n! is defined to be 1.
int Factorial(int n) {
  int result = 1;
  for (int i = 1; i <= n; i++) {
    result *= i;
  }

  return result;
}

// Returns true iff n is a prime number.
bool IsPrime(int n) {
  // Trivial case 1: small numbers
  if (n <= 1) return false;

  // Trivial case 2: even numbers
  if (n % 2 == 0) return n == 2;

  // Now, we have that n is odd and n >= 3.

  // Try to divide n by every odd number i, starting from 3
  for (int i = 3; ; i += 2) {
    // We only have to try i up to the square root of n
    if (i > n/i) break;

    // Now, we have i <= n/i < n.
    // If n is divisible by i, n is not prime.
    if (n % i == 0) return false;
  }

  // n has no integer factor in the range (1, n), and thus is prime.
  return true;
}

sample1_unittest.cc

#include <limits.h>
#include "sample1.h"
#include "gtest/gtest.h"
namespace {

// Tests Factorial().

// Tests factorial of negative numbers.
TEST(FactorialTest, Negative) {
  // This test is named "Negative", and belongs to the "FactorialTest"
  // test case.
  EXPECT_EQ(1, Factorial(-5)) << "this sunrise test"; //後面的信息在失敗的情況下輸出到終端
  EXPECT_EQ(1, Factorial(-1));
  EXPECT_GT(Factorial(-10), 0);

// Tests factorial of 0.
TEST(FactorialTest, Zero) {
  EXPECT_EQ(1, Factorial(0));
}

// Tests factorial of positive numbers.
TEST(FactorialTest, Positive) {
  EXPECT_EQ(1, Factorial(1));
  EXPECT_EQ(2, Factorial(2));
  EXPECT_EQ(6, Factorial(3));
  EXPECT_EQ(40320, Factorial(8));
}


// Tests IsPrime()

// Tests negative input.
TEST(IsPrimeTest, Negative) {
  // This test belongs to the IsPrimeTest test case.

  EXPECT_FALSE(IsPrime(-1));
  EXPECT_FALSE(IsPrime(-2));
  EXPECT_FALSE(IsPrime(INT_MIN));
}

// Tests some trivial cases.
TEST(IsPrimeTest, Trivial) {
  EXPECT_FALSE(IsPrime(0));
  EXPECT_FALSE(IsPrime(1));
  EXPECT_TRUE(IsPrime(2));
  EXPECT_TRUE(IsPrime(3));
}

// Tests positive input.
TEST(IsPrimeTest, Positive) {
  EXPECT_FALSE(IsPrime(4));
  EXPECT_TRUE(IsPrime(5));
  EXPECT_FALSE(IsPrime(6));
  EXPECT_TRUE(IsPrime(23));
}
} // namespace

main.cpp

#include<iostream>
#include<gtest/gtest.h>

using namespace std;

GTEST_API_ int main(int argc, char **argv) {
    printf("Running main");
    testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

編譯命令:

g++ sample1.cc sample1.h sample1_unittest.cc main.cpp -lgtest -lpthread -o main

運行效果如下:

Running main[==========] Running 6 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 3 tests from FactorialTest
[ RUN      ] FactorialTest.Negative
[       OK ] FactorialTest.Negative (0 ms)
[ RUN      ] FactorialTest.Zero
[       OK ] FactorialTest.Zero (0 ms)
[ RUN      ] FactorialTest.Positive
[       OK ] FactorialTest.Positive (0 ms)
[----------] 3 tests from FactorialTest (0 ms total)

[----------] 3 tests from IsPrimeTest
[ RUN      ] IsPrimeTest.Negative
[       OK ] IsPrimeTest.Negative (0 ms)
[ RUN      ] IsPrimeTest.Trivial
[       OK ] IsPrimeTest.Trivial (0 ms)
[ RUN      ] IsPrimeTest.Positive
[       OK ] IsPrimeTest.Positive (0 ms)
[----------] 3 tests from IsPrimeTest (0 ms total)

[----------] Global test environment tear-down
[==========] 6 tests from 2 test cases ran. (0 ms total)
[  PASSED  ] 6 tests.

更改FactorialTest.Negative中的用例代碼

// EXPECT_EQ(1, Factorial(-5)) << "this sunrise test"; //後面的信息在失敗的情況下輸出到終端
EXPECT_EQ(-1, Factorial(-5)) << "this sunrise test";

運行效果:

Running main[==========] Running 6 tests from 2 test cases.
[----------] Global test environment set-up.
[----------] 3 tests from FactorialTest
[ RUN      ] FactorialTest.Negative
sample1_unittest.cc:79: Failure
Value of: Factorial(-5)
  Actual: 1
Expected: -1
this sunrise test
[  FAILED  ] FactorialTest.Negative (0 ms)
[ RUN      ] FactorialTest.Zero
[       OK ] FactorialTest.Zero (0 ms)
[ RUN      ] FactorialTest.Positive
[       OK ] FactorialTest.Positive (0 ms)
[----------] 3 tests from FactorialTest (0 ms total)

[----------] 3 tests from IsPrimeTest
[ RUN      ] IsPrimeTest.Negative
[       OK ] IsPrimeTest.Negative (0 ms)
[ RUN      ] IsPrimeTest.Trivial
[       OK ] IsPrimeTest.Trivial (0 ms)
[ RUN      ] IsPrimeTest.Positive
[       OK ] IsPrimeTest.Positive (0 ms)
[----------] 3 tests from IsPrimeTest (0 ms total)

[----------] Global test environment tear-down
[==========] 6 tests from 2 test cases ran. (0 ms total)
[  PASSED  ] 5 tests.
[  FAILED  ] 1 test, listed below:
[  FAILED  ] FactorialTest.Negative

 1 FAILED TEST

基礎語法介紹

斷言

分爲ASSERT_*和EXPECT_*兩種類型:

ASSERT_* EXPECT_*
致命的斷言,終止當前功能(以測試用例爲組) 非致命故障,不會終止當前功能

終止:是終止自身處於的那一組測試用例,如上例中的FactorialTest.Negative是一組測試。

斷言詳細函數
  • 基本函數,基本的真/假條件測試。
Fatal assertion Nonfatal assertion Verifies
ASSERT_TRUE(condition); EXPECT_TRUE(condition); condition is true
ASSERT_FALSE(condition); EXPECT_FALSE(condition); condition is false
  • 二元比較
Fatal assertion Nonfatal assertion Verifies
ASSERT_EQ(val1, val2); EXPECT_EQ(val1, val2); val1 == val2
ASSERT_NE(val1, val2); EXPECT_NE(val1, val2); val1 != val2
ASSERT_LT(val1, val2); EXPECT_LT(val1, val2); val1 < val2
ASSERT_LE(val1, val2); EXPECT_LE(val1, val2); val1 <= val2
ASSERT_GT(val1, val2); EXPECT_GT(val1, val2); val1 > val2
ASSERT_GE(val1, val2); EXPECT_GE(val1, val2); val1 >= val2
  • 字符串比較
Fatal assertion Nonfatal assertion Verifies
ASSERT_STREQ(str1, str2); EXPECT_STREQ(str1, str2); the two C strings have the same content
ASSERT_STRNE(str1, str2); EXPECT_STRNE(str1, str2); the two C strings have different contents
ASSERT_STRCASEEQ(str1, str2); EXPECT_STRCASEEQ(str1, str2); the two C strings have the same content, ignoring case
ASSERT_STRCASENE(str1, str2); EXPECT_STRCASENE(str1, str2); the two C strings have different contents, ignoring case
Test Fixtures: 爲多個測試使用相同的數據配置

Fixtures 是測試中非常重要的一部分。他們的主要目的是建立一個固定/已知的環境狀態以確保 測試可重複並且按照預期方式運行。

  1. 創建Fixture類繼承至::testing::Test.
  2. 在類中,聲明需要使用的對象
  3. 編寫SetUp函數
  4. 編寫TearDown函數
  5. 如果需要,請爲要共享的測試定義子例程。

例子:
Fixtures類

class QueueTest : public ::testing::Test {
 protected:
  void SetUp() override {
     q1_.Enqueue(1);
     q2_.Enqueue(2);
     q2_.Enqueue(3);
  }

  // void TearDown() override {}

  Queue<int> q0_;
  Queue<int> q1_;
  Queue<int> q2_;
};

測試用例

TEST_F(QueueTest, IsEmptyInitially) {
  EXPECT_EQ(q0_.size(), 0);
}

TEST_F(QueueTest, DequeueWorks) {
  // construct an instance QueueTest q;q.SetUp()
  int* n = q0_.Dequeue();
  EXPECT_EQ(n, nullptr);

  n = q1_.Dequeue();
  ASSERT_NE(n, nullptr);
  EXPECT_EQ(*n, 1);
  EXPECT_EQ(q1_.size(), 0);
  delete n;

  n = q2_.Dequeue();
  ASSERT_NE(n, nullptr);
  EXPECT_EQ(*n, 2);
  EXPECT_EQ(q2_.size(), 1);
  delete n;
  // q.TearDown()
}

用例一和用例公用的QueueTest中的q0_,q1_,q2_,SetUp()和TearDown().

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章