VSCode + CMake + GoogleTest 实现 C++ 单元测试
VSCode + CMake + GoogleTest 实现 C++ 单元测试
参考视频:https://www.bilibili.com/video/BV1hpRpYZE7d/
安装 CMake
执行命令:
brew install cmake
验证版本:

VS code 安装 CMake Tools 拓展
搜索并安装:

下载 GoogleTest 源码
在项目中,执行命令:
git clone https://gitee.com/mirrors/googletest.git
编写项目代码
max.h:
#pragma once
int max(int a, int b);
max.cpp:
int max(int a, int b)
{
return a > b ? a : b;
}
main.cpp:
#include <iostream>
#include "max.h"
using namespace std;
int main()
{
cout << "Hello World" << endl;
cout << "Max of 3 and 5 is: " << max(3, 5) << endl;
return 0;
}
构建 CMake
- 点击 VS code 上面的搜索框,选择“显示并运行命令”

- 输入 cmake quick…,点击“CMake:快速入门”

- 点击“添加新预设”

- 点击“从编译器创建”

- 这里我选择本地的 Clang 17.0.0

- 输入预设名字,直接回车跳过

- 输入新项目的名称,必须填写

- 选择“创建 C++ 项目”

- 选择“创建可执行文件”

- 勾选 CTest,点击“确定”

- 勾选上当前项目中的两个 cpp 文件

生成的 CMakeLists.txt:
cmake_minimum_required(VERSION 3.10.0)
project(max_demo VERSION 0.1.0 LANGUAGES C CXX)
add_executable(max_demo main.cpp max.cpp)
include(CTest)
enable_testing()
生成的 CMakePresets.json:
{
"version": 8,
"configurePresets": [
{
"name": "Clang 17.0.0 arm64-apple-darwin24.6.0",
"displayName": "Clang 17.0.0 arm64-apple-darwin24.6.0",
"description": "正在使用编译器: C = /usr/bin/clang, CXX = /usr/bin/clang++",
"binaryDir": "${sourceDir}/out/build/${presetName}",
"cacheVariables": {
"CMAKE_INSTALL_PREFIX": "${sourceDir}/out/install/${presetName}",
"CMAKE_C_COMPILER": "/usr/bin/clang",
"CMAKE_CXX_COMPILER": "/usr/bin/clang++",
"CMAKE_BUILD_TYPE": "Debug"
}
}
]
}
添加测试
test_max.cpp:
#include "gtest/gtest.h"
#include "max.h"
TEST(Max, MaxOf3And5)
{
EXPECT_EQ(5, max(3, 5));
}
TEST(Max, MaxOf10And5)
{
EXPECT_NE(5, max(10, 5));
}
向 CMakeLists.txt 添加:
add_subdirectory(googletest)
add_executable(test_max test_max.cpp max.cpp)
target_link_libraries(test_max gtest_main)
add_test(NAME test_max COMMAND test_max)
打开 CMake Tools,点击生成右侧的按钮:

生成成功:

在项目大纲中,可以看到 main.cpp 对应的 max_demo,点击右侧的按钮,生成成功:

点击启动右侧的运行按钮,main 函数执行并输出:

同理,test_max.cpp 对应的 test_max,点击右侧的按钮,生成成功:

可以修改启动目标:


改成 test_max:

再次运行:

两个测试都通过了。
以测试程序分类,也可以一览测试的通过与否:


通过 CMake 工具实现依赖下载
删除项目中的 googletest 文件夹。
修改 CMakeLists.txt:
cmake_minimum_required(VERSION 3.10.0)
project(max_demo VERSION 0.1.0 LANGUAGES C CXX)
# 添加主程序
add_executable(max_demo main.cpp max.cpp)
# 下载并包含 GoogleTest
include(FetchContent)
FetchContent_Declare(
googletest
# 对于 GoogleTest 1.11以及后续版本,可能需要使用 GIT_REPOSITORY 和 GIT_TAG 来代替 URL
URL https://gitee.com/mirrors/googletest/repository/archive/main.zip
)
# 下载并使 GoogleTest 可用
FetchContent_MakeAvailable(googletest)
# 启用测试
include(CTest)
enable_testing()
# 添加测试可执行文件
add_executable(test_max test_max.cpp max.cpp)
# 链接 GoogleTest
target_link_libraries(test_max gtest_main)
# 注册测试
add_test(NAME test_max COMMAND test_max)
构建成功:

GoogleTest 源码也会下载到项目中:

测试通过:

268

被折叠的 条评论
为什么被折叠?



