平台要求

基本概念

gtest 特性

  • 不限于 unit tests
  • 测试独立性和可重复性
  • 测试编组
  • 可移植和重用性,平台中立性
  • 一个测试失败,不影响其他测试继续进行
  • 不需要运行编排
  • 运行快速
  • 基于 xUnit 框架

    • 即类似于 JUnit 和 PyUnit

概念辨析

  1. Test

    • 使用断言实现
  2. TestCase –> 相当于其他框架中的 TestSuite

    • 包含一个或多个 Test
  3. TestSuite

    • 在 gtest 中和 TestCase 等价
  4. 注意

    • gtest 会逐步把 TestCase 变成 TestSuite, 术语替换

断言

  • 两种类型

    • ASSERT_*

      • 断言失败,致命错误,终止程序
      • 注意

        • 谨慎使用,会跳过后续内存清理代码,导致内存泄漏
    • EXPECT_*

      • 断言失败,非致命错误,不会立刻终止程序

TEST 宏

  1. 用途

    • 声明一个 Test,制定归属 TestCase
  2. 参数

    1. TestCase 名
    2. Test 名

TEST_F 宏

  • 用途: 设置公共配置信息,即 Test Fixtures
  • 相关函数

    • SetUp()
    • TearDown()
  • 参数

    1. 自定义 Test Fixture 类名

      • 注意

        • fixture 必须提前声明
    2. Test 名

Test 和 TestSuite 命名要求

  • eg: TestName, TestPositiveInput
  • 不允许有下划线

Fixture

  • 要求

    • 需要继承自类 ::testing::Test

      • protected: 开头
    • 配置方法

      • SetUp()
      • tearDown()
      • 公用方法
      • 注意

        • 这些都是可选的
  • 调用

    • 使用 TEST_F()
  • 注意

    • 不同 Test 使用的是不同 fixture 实例

运行 tests 方法

  • 编写 main() 函数

    1. 调用 ::testing::InitGoogleTest 函数
    2. 调用 RUN_ALL_TESTS() 宏

      • 注意

        • 只能调用一次
        • 它会自动完成 fixture 的配置和 test 的运行安排
      • 示例

        1
        2
        3
        4
        
          int main(int argc, char **argv) {
            ::testing::InitGoogleTest(&argc, argv);   // 注意: **** 必不可少 *****
            return RUN_ALL_TESTS();
          }
  • 直接调用 gest_main 库

cmake 调用

  • 例子

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    cmake_minimum_required(VERSION 3.14)
    project(my_project)
    
    # ------------ 配置 gtest -----------------------
    # GoogleTest requires at least C++11
    set(CMAKE_CXX_STANDARD 11)
    
    include(FetchContent)
    FetchContent_Declare(
      googletest
      URL https://github.com/google/googletest/archive/609281088cfefc76f9d0ce82e1ff6c30cc3591e5.zip
    )
    # For Windows: Prevent overriding the parent project's compiler/linker settings
    set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
    FetchContent_MakeAvailable(googletest)
    # -------------------------------------------------
    
    # ------------ 创建 gtest target(可执行文件) 和 整合 ctest (cmake test)
    enable_testing()
    
    add_executable(
      hello_test
      hello_test.cc
    )
    target_link_libraries(
      hello_test
      gtest_main
    )
    
    include(GoogleTest)
    gtest_discover_tests(hello_test)
  • 调用

    • 使用 ctest 命令 运行测试

      1
      2
      3
      4
      5
      
      my_project$ cmake -S . -B build
      
      my_project$ cmake --build build
      
      my_project$ cd build && ctest