Google Test(gtest) Notes
文章目录
平台要求
- 编译器 >= C++ 11
- gcc5.0+
- clang5.0+
- msvc2015+
- 参考:https://google.github.io/googletest/platforms.html
基本概念
gtest 特性
- 不限于 unit tests
- 测试独立性和可重复性
- 测试编组
- 可移植和重用性,平台中立性
- 一个测试失败,不影响其他测试继续进行
- 不需要运行编排
- 运行快速
基于 xUnit 框架
- 即类似于 JUnit 和 PyUnit
概念辨析
Test
- 使用断言实现
TestCase –> 相当于其他框架中的 TestSuite
- 包含一个或多个 Test
TestSuite
- 在 gtest 中和 TestCase 等价
注意
- gtest 会逐步把 TestCase 变成 TestSuite,
术语替换
- gtest 会逐步把 TestCase 变成 TestSuite,
断言
两种类型
ASSERT_*
- 断言失败,致命错误,终止程序
注意
- 谨慎使用,会跳过后续内存清理代码,导致内存泄漏
EXPECT_*
- 断言失败,非致命错误,不会立刻终止程序
TEST 宏
用途
- 声明一个 Test,制定归属 TestCase
参数
- TestCase 名
- Test 名
TEST_F 宏
- 用途: 设置公共配置信息,即 Test Fixtures
相关函数
- SetUp()
- TearDown()
参数
自定义 Test Fixture 类名
注意
- fixture 必须提前声明
- Test 名
Test 和 TestSuite 命名要求
- eg: TestName, TestPositiveInput
- 不允许有下划线
Fixture
要求
需要继承自类
::testing::Test- 以
protected:开头
- 以
配置方法
- SetUp()
- tearDown()
- 公用方法
注意
- 这些都是可选的
调用
- 使用
TEST_F()宏
- 使用
注意
- 不同 Test 使用的是不同 fixture 实例
运行 tests 方法
编写 main() 函数
- 调用
::testing::InitGoogleTest函数 调用 RUN_ALL_TESTS() 宏
注意
- 只能调用一次
- 它会自动完成 fixture 的配置和 test 的运行安排
示例
1 2 3 4int 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 31cmake_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 5my_project$ cmake -S . -B build my_project$ cmake --build build my_project$ cd build && ctest
文章作者
上次更新 2023-02-10 (97c415e)