GTest和Catch2是C++主流测试框架,前者适合大型项目,支持丰富断言与CI集成,后者轻量简洁,单头文件易用,推荐根据项目需求选择。

在C++开发中,单元测试是保障代码质量的重要手段。GTest(Google Test)和Catch2是目前最流行的两个C++单元测试框架,它们都支持跨平台、语法简洁,并能快速集成到项目中。下面介绍如何使用这两个框架进行单元测试。
GTest 是 Google 开发的 C++ 测试框架,功能强大,适合大型项目。
1. 安装与配置 GTest
你可以通过包管理器或源码编译安装 GTest:
Linux/macOS(使用 vcpkg):
vcpkg install gtest
立即学习“C++免费学习笔记(深入)”;
Linux(使用 apt):
sudo apt-get install libgtest-dev cmake,然后需手动编译 gtest 源码
直接构建(推荐用于学习): 下载源码并编译:
git clone https://github.com/google/googletest.git
cd googletest && mkdir build && cd build
cmake .. && make -j
sudo make install
2. 编写第一个 GTest 测试
假设你有一个简单函数需要测试:
// math_utils.h
int add(int a, int b);
// math_utils.cpp
int add(int a, int b) { return a + b; }
创建测试文件 test_math.cpp:
#include <gtest/gtest.h>
#include "math_utils.h"
TEST(MathTest, AddFunction) {
EXPECT_EQ(add(2, 3), 5);
EXPECT_EQ(add(-1, 1), 0);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
3. 编译并运行测试
使用 CMake 构建项目示例:
# CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(MyTestProject)
enable_testing()
set(CMAKE_CXX_STANDARD 17)
add_executable(test_math test_math.cpp math_utils.cpp)
target_link_libraries(test_math gtest_main gtest pthread)
编译:
mkdir build && cd build
cmake .. && make
./test_math
输出会显示测试通过或失败信息。
4. 常用断言
Catch2 是一个单头文件、轻量级的现代 C++ 测试框架,使用更简洁。
1. 集成 Catch2
最简单方式是下载 catch2 的单头文件版本:
wget https://github.com/catchorg/Catch2/releases/download/v3.4.0/catch_amalgamated.hpp
将其放入项目 include 目录,如: catch2.hpp
2. 编写 Catch2 测试
同样测试 add 函数:
#define CATCH_CONFIG_MAIN
#include "catch2.hpp"
#include "math_utils.h"
TEST_CASE("Addition works", "[math]") {
REQUIRE(add(2, 3) == 5);
REQUIRE(add(-1, 1) == 0);
}
注意: #define CATCH_CONFIG_MAIN 应只在一个测试文件中定义,否则会重复定义 main 函数。若多个测试文件,可改用 #define CATCH_CONFIG_RUNNER 并自定义 main。
3. 编译 Catch2 测试
CMake 示例:
add_executable(test_math_catch test_math_catch.cpp math_utils.cpp)
target_include_directories(test_math_catch PRIVATE ./catch2) # 包含 catch2.hpp 所在目录
编译后运行:
./test_math_catch
支持标签过滤、生成报告等功能:
./test_math_catch [math] --reporter xml
4. Catch2 常用宏
两个框架各有优势:
通用建议:
基本上就这些。根据项目规模和个人偏好选择合适的框架即可。
以上就是c++++如何使用GTest或Catch2进行单元测试_c++测试框架使用指南的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号