google gtest框架入门使用案例

打印 上一主题 下一主题

主题 914|帖子 914|积分 2742

通过本文可以收获:google gtest急速入门、google gtest资源网站。
google gtest是什么

google gtest是谷歌开源的c++单元测试框架,非常的好用。
起码个人感觉和spring boot自带的测试框架功能差不太多。
安装

略过,请参考:GitHub - google/googletest: GoogleTest - Google Testing and Mocking Framework或网上资料
使用案例分析

本文重点。
目前版本样例位于:googletest/googletest/samples at main · google/googletest中。
断言

与spring boot的测试框架类似,gtest判断样例是否出错用的也是断言。
断言使用(ASSERT或EXPECT)和配合上具体内容,下面案例应该是一看就懂。
ASSERT和EXPECT的区别只在于一个函数中,如果有多个断言,ASSERT断言失败后当前函数后续部分不会执行了,EXPECT断言失败后当前函数的后续部分会继续执行。
因此两种具体用哪一个需要看 当前断言失败后函数后续还有无意义。
基础的断言

Fatal assertionNonfatal assertionVerifiesASSERT_TRUE(condition);EXPECT_TRUE(condition);condition is trueASSERT_FALSE(condition);EXPECT_FALSE(condition);condition is false数值比较

Fatal assertionNonfatal assertionVerifiesASSERT_EQ(val1, val2);EXPECT_EQ(val1, val2);val1 == val2ASSERT_NE(val1, val2);EXPECT_NE(val1, val2);val1 != val2ASSERT_LT(val1, val2);EXPECT_LT(val1, val2);val1 < val2ASSERT_LE(val1, val2);EXPECT_LE(val1, val2);val1  val2ASSERT_GE(val1, val2);EXPECT_GE(val1, val2);val1 >= val2字符串比较

Fatal assertionNonfatal assertionVerifiesASSERT_STREQ(str1, str2);EXPECT_STREQ(str1, _str_2);the two C strings have the same contentASSERT_STRNE(str1, str2);EXPECT_STRNE(str1, str2);the two C strings have different contentASSERT_STRCASEEQ(str1, str2);EXPECT_STRCASEEQ(str1, str2);the two C strings have the same content, ignoring caseASSERT_STRCASENE(str1, str2);EXPECT_STRCASENE(str1, str2);the two C strings have different content, ignoring case
上面内容并不完整,gtest还有些厉害的功能,比如ASSERT_NEAR(ASSERT_NEAR(res, 3.0, 1.0e-11);)用于断言数字的接近程度,当然这种功能已经可以由基础的组合而成了。
个人样例分析

在配置好环境后来一个最简单的入门吧。
公司这边使用的是集成的插件,具体配置vscode + gtest请自行探索。
  1. /*
  2. * Copyright (c) Huawei Technologies Co., Ltd. 2019-2020. All rights reserved.
  3. */
  4. #include "gtest/gtest.h"
  5. #include "leetcode24.h" //要测试的函数的头文件,其中有要测试的函数
  6. int main(int argc, char** argv)
  7. {
  8.     ::testing::InitGoogleTest(&argc, argv);
  9.     return RUN_ALL_TESTS();
  10. }
  11. TEST(leetcode24, add1)
  12. {
  13.     double res = AddNumbers(1.0, 2.0);
  14.     ASSERT_NEAR(res, 3.0, 1.0e-11);
  15. }
复制代码
编译后点击测试即可:

可以观察到左边名字和右边TEST宏中有对应,TEST的传入的参数只是名字,没有其他含义。
这里是已经测试成功了,除了图形化也可以在命令行进行测试:
  1. 正在执行任务: cd build && cmake --build . --target all && ctest -j14 -C Debug -T test --verbose
  2. [2/2] Linking CXX executable ..\bin\test_leetcode24.exe
  3. UpdateCTestConfiguration  from :C:/Users/cWX1274913/Desktop/self/leetcode/leetcode24/build/DartConfiguration.tcl
  4. Parse Config file:C:/Users/cWX1274913/Desktop/self/leetcode/leetcode24/build/DartConfiguration.tcl
  5.    Site: P_CDTFC3-N64RRS
  6.    Build name: Win32-ninja
  7. UpdateCTestConfiguration  from :C:/Users/cWX1274913/Desktop/self/leetcode/leetcode24/build/DartConfiguration.tcl
  8. Parse Config file:C:/Users/cWX1274913/Desktop/self/leetcode/leetcode24/build/DartConfiguration.tcl
  9. Test project C:/Users/cWX1274913/Desktop/self/leetcode/leetcode24/build
  10. Constructing a list of tests
  11. Done constructing a list of tests
  12. Updating test list for fixtures
  13. Added 0 tests to meet fixture requirements
  14. Checking test dependency graph...
  15. Checking test dependency graph end
  16. test 1
  17.     Start 1: test
  18. 1: Test command: C:\Users\cWX1274913\Desktop\self\leetcode\leetcode24\bin\test_leetcode24.exe
  19. 1: Test timeout computed to be: 1500
  20. 1: [==========] Running 1 test from 1 test case.
  21. 1: [----------] Global test environment set-up.
  22. 1: [----------] 1 test from leetcode24
  23. 1: [ RUN      ] leetcode24.add1
  24. 1: [       OK ] leetcode24.add1 (0 ms)
  25. 1: [----------] 1 test from leetcode24 (0 ms total)
  26. 1:
  27. 1: [----------] Global test environment tear-down
  28. 1: [==========] 1 test from 1 test case ran. (0 ms total)
  29. 1: [  PASSED  ] 1 test.
  30. 1/1 Test #1: test .............................   Passed    0.10 sec
  31. 100% tests passed, 0 tests failed out of 1
  32. Total Test time (real) =   0.12 sec
  33. *  终端将被任务重用,按任意键关闭。
复制代码
可以看到测试已经成功了,来个失败的案例吧。
增加两个test案例,分别是ASSERT和EXPECT的失败案例。
  1. TEST(leetcode24, assertFail)
  2. {
  3.     double res = AddNumbers2(1.0, 2.0);
  4.     // EXPECT_NEAR(res, 4.0, 1.0e-11);
  5.     ASSERT_NEAR(res, 4.0, 1.0e-11);
  6.     res = 3;
  7.     EXPECT_NEAR(res, 3.0, 1.0e-11);
  8. }
  9. TEST(leetcode24, expextFail)
  10. {
  11.     double res = AddNumbers2(1.0, 2.0);
  12.     EXPECT_NEAR(res, 4.0, 1.0e-11);
  13.     res = 3;
  14.     EXPECT_NEAR(res, 3.0, 1.0e-11);
  15. }
复制代码
运行后的命令行:
  1. test 1
  2.     Start 1: test
  3. 1: Test command: C:\Users\cWX1274913\Desktop\self\leetcode\leetcode24\bin\test_leetcode24.exe
  4. 1: Test timeout computed to be: 1500
  5. 1: [==========] Running 3 tests from 1 test case.
  6. 1: [----------] Global test environment set-up.
  7. 1: [----------] 3 tests from leetcode24
  8. 1: [ RUN      ] leetcode24.add1
  9. 1: [       OK ] leetcode24.add1 (0 ms)
  10. 1: [ RUN      ] leetcode24.assertFail
  11. 1: ../test/test_leetcode24.cpp:23: Failure
  12. 1: The difference between res and 4.0 is 1, which exceeds 1.0e-11, where
  13. 1: res evaluates to 3,
  14. 1: 4.0 evaluates to 4, and
  15. 1: 1.0e-11 evaluates to 9.9999999999999994e-12.
  16. 1: [  FAILED  ] leetcode24.assertFail (0 ms)
  17. 1: [ RUN      ] leetcode24.expextFail
  18. 1: ../test/test_leetcode24.cpp:32: Failure
  19. 1: The difference between res and 4.0 is 1, which exceeds 1.0e-11, where
  20. 1: res evaluates to 3,
  21. 1: 4.0 evaluates to 4, and
  22. 1: 1.0e-11 evaluates to 9.9999999999999994e-12.
  23. 1: ../test/test_leetcode24.cpp:34: Failure
  24. 1: The difference between res and 4.0 is 1, which exceeds 1.0e-11, where
  25. 1: res evaluates to 3,
  26. 1: 4.0 evaluates to 4, and
  27. 1: 1.0e-11 evaluates to 9.9999999999999994e-12.
  28. 1: [  FAILED  ] leetcode24.expextFail (0 ms)
  29. 1: [----------] 3 tests from leetcode24 (0 ms total)
  30. 1:
  31. 1: [----------] Global test environment tear-down
  32. 1: [==========] 3 tests from 1 test case ran. (0 ms total)
  33. 1: [  PASSED  ] 1 test.
  34. 1: [  FAILED  ] 2 tests, listed below:
  35. 1: [  FAILED  ] leetcode24.assertFail
  36. 1: [  FAILED  ] leetcode24.expextFail
  37. 1:
  38. 1:  2 FAILED TESTS
  39. 1/1 Test #1: test .............................***Failed    0.04 sec
  40. 0% tests passed, 1 tests failed out of 1
  41. Total Test time (real) =   0.06 sec
复制代码
可以看到leetcode24.assertFail有一处失败,而leetcode24.expextFail有两处失败。这 验证 ASSERT断言失败后续不会再执行,而EXCEPT断言失败后续还会继续执行。
TEST_F宏

TEST_F宏的作用在于帮助很多类似的处理进行批量测试。如果我们使用的测试集需要使用一些相似的数据呢?或者有些相似的检查方法?这时就需要用到测试夹具和TEST_F宏配合了。
测试夹具和TEST_F宏 的最大的作用就在于测试开始之前和测试完成之后可以执行对应的函数,SetUp 和 TearDown 两个虚函数。
  1. #include "sample3-inl.h"
  2. #include "gtest/gtest.h"
  3. // To use a test fixture, derive a class from testing::Test.
  4. class QueueTest : public testing::Test {
  5. protected:  // You should make the members protected s.t. they can be
  6.              // accessed from sub-classes.
  7.   // virtual void SetUp() will be called before each test is run.  You
  8.   // should define it if you need to initialize the varaibles.
  9.   // Otherwise, this can be skipped.
  10.   virtual void SetUp() {
  11.     q1_.Enqueue(1);
  12.     q2_.Enqueue(2);
  13.     q2_.Enqueue(3);
  14.   }
  15.   // virtual void TearDown() will be called after each test is run.
  16.   // You should define it if there is cleanup work to do.  Otherwise,
  17.   // you don't have to provide it.
  18.   //
  19.   // virtual void TearDown() {
  20.   // }
  21.   // A helper function that some test uses.
  22.   static int Double(int n) {
  23.     return 2*n;
  24.   }
  25.   // A helper function for testing Queue::Map().
  26.   void MapTester(const Queue<int> * q) {
  27.     // Creates a new queue, where each element is twice as big as the
  28.     // corresponding one in q.
  29.     const Queue<int> * const new_q = q->Map(Double);
  30.     // Verifies that the new queue has the same size as q.
  31.     ASSERT_EQ(q->Size(), new_q->Size());
  32.     // Verifies the relationship between the elements of the two queues.
  33.     for ( const QueueNode<int> * n1 = q->Head(), * n2 = new_q->Head();
  34.           n1 != NULL; n1 = n1->next(), n2 = n2->next() ) {
  35.       EXPECT_EQ(2 * n1->element(), n2->element());
  36.     }
  37.     delete new_q;
  38.   }
  39.   // Declares the variables your tests want to use.
  40.   Queue<int> q0_;
  41.   Queue<int> q1_;
  42.   Queue<int> q2_;
  43. };
  44. // When you have a test fixture, you define a test using TEST_F
  45. // instead of TEST.
  46. // Tests the default c'tor.
  47. TEST_F(QueueTest, DefaultConstructor) {
  48.   // You can access data in the test fixture here.
  49.   EXPECT_EQ(0u, q0_.Size());
  50. }
  51. // Tests Dequeue().
  52. TEST_F(QueueTest, Dequeue) {
  53.   int * n = q0_.Dequeue();
  54.   EXPECT_TRUE(n == NULL);
  55.   n = q1_.Dequeue();
  56.   ASSERT_TRUE(n != NULL);
  57.   EXPECT_EQ(1, *n);
  58.   EXPECT_EQ(0u, q1_.Size());
  59.   delete n;
  60.   n = q2_.Dequeue();
  61.   ASSERT_TRUE(n != NULL);
  62.   EXPECT_EQ(2, *n);
  63.   EXPECT_EQ(1u, q2_.Size());
  64.   delete n;
  65. }
  66. // Tests the Queue::Map() function.
  67. TEST_F(QueueTest, Map) {
  68.   MapTester(&q0_);
  69.   MapTester(&q1_);
  70.   MapTester(&q2_);
  71. }
复制代码
可以看到我们首先需要从 testing::Test 来派生一个自己的测试类QueueTest,在这个类里你可以定义一些必要的成员变量或者辅助函数,还可以定义 SetUp 和 TearDown 两个虚函数,来指定每个测试集运行前和运行后应该做什么。后面测试用例的每个测试集应该使用 TEST_F 宏,第一个参数是我们定义的类名,第二个是测试集的名称。
这样就可以避免在很多重复的测试的时候需要不断重复初始化相同的内容了,以及可以利用类的函数来写一些复杂的运行逻辑。
参考:
https://github.com/google/googletest/blob/main/googletest/samples/sample6_unittest.cc
https://github.com/AngryHacker/articles/blob/master/src/open_source_components/google_gtest.md
我的博客园:https://www.cnblogs.com/swx123
我的github(代码一般都放在这里):https://github.com/578223592

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

乌市泽哥

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表