切换主题
C++ 测试库
本文档介绍常用的 C++ 测试库及其使用方法,包括 Google Test 和 Catch2。
Google Test (GTest)
简介
Google Test 是一个流行的 C++ 单元测试框架,支持断言、测试套件和测试运行器,适合大规模项目的单元测试。
安装与配置
克隆 Google Test 源码:
bashgit clone https://github.com/google/googletest.git
1使用 CMake 构建并安装:
bashcd googletest cmake -S . -B build cmake --build build --target install
1
2
3在项目中包含头文件:
cpp#include <gtest/gtest.h>
1
示例代码
以下是一个简单的 Google Test 示例:
cpp
// filepath: d:\Docs\huaqiwill-dev-docs\编程语言\C++\扩展库\C++测试库.md
#include <gtest/gtest.h>
// 被测试函数
int add(int a, int b) {
return a + b;
}
// 测试用例
TEST(AdditionTest, PositiveNumbers) {
EXPECT_EQ(add(2, 3), 5);
}
TEST(AdditionTest, NegativeNumbers) {
EXPECT_EQ(add(-2, -3), -5);
}
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
运行测试
编译并运行测试:
bash
g++ -std=c++11 -isystem /path/to/gtest/include -pthread test.cpp -L/path/to/gtest/lib -lgtest -lgtest_main -o test
./test
1
2
2
Catch2
简介
Catch2 是一个现代化的 C++ 测试框架,支持单头文件分发,语法简洁,适合快速开发和小型项目。
安装与配置
- 下载 Catch2 单头文件:bash
wget https://github.com/catchorg/Catch2/releases/download/v2.13.10/catch.hpp
1 - 在项目中包含
catch.hpp
:cpp#include "catch.hpp"
1
示例代码
以下是一个简单的 Catch2 示例:
cpp
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
// 被测试函数
int multiply(int a, int b) {
return a * b;
}
// 测试用例
TEST_CASE("Multiplication", "[math]") {
REQUIRE(multiply(2, 3) == 6);
REQUIRE(multiply(-2, 3) == -6);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
2
3
4
5
6
7
8
9
10
11
12
13
运行测试
编译并运行测试:
bash
g++ -std=c++11 test.cpp -o test
./test
1
2
2
对比
特性 | Google Test | Catch2 |
---|---|---|
安装方式 | CMake 构建 | 单头文件 |
学习曲线 | 较陡峭 | 较平缓 |
适用场景 | 大型项目 | 小型项目或快速开发 |
断言支持 | 丰富 | 简洁 |