Google Test 是一个流行的 C++ 单元测试框架,可以帮助开发人员编写高质量的测试用例。CMake 是一个跨平台的构建系统,可以生成不同平台的构建文件,包括 Makefile 和 Visual Studio 等。
下面是一个使用 CMake 构建 Google Test 示例项目的步骤:
在项目的根目录下创建如下的目录结构:
project/
CMakeLists.txt
src/
main.cpp
include/
hello.h
test/
CMakeLists.txt
hello_test.cpp
其中,src 目录下存放项目的源代码,include 目录下存放头文件,test 目录下存放测试代码。
配置 CMakeLists.txt
在项目的根目录下创建 CMakeLists.txt 文件,添加如下内容:
cmake_minimum_required(VERSION 3.10)
project(project)
# 添加 Google Test 子目录
add_subdirectory(googletest)
# 设置可执行文件的名称和源文件
add_executable(main src/main.cpp)
# 添加头文件路径
target_include_directories(main PRIVATE include)
# 添加链接库
target_link_libraries(main gtest)
# 添加测试子目录
add_subdirectory(test)
上面的 CMakeLists.txt 文件中,我们首先设置了项目的名称,并添加了 Google Test 子目录。然后,我们设置了可执行文件的名称和源文件,并添加了头文件路径和链接库。最后,我们添加了测试子目录。
配置 test/CMakeLists.txt
在 test 目录下创建 CMakeLists.txt 文件,添加如下内容:
# 添加测试文件
add_executable(hello_test hello_test.cpp)
# 添加头文件路径
target_include_directories(hello_test PRIVATE ${gtest_SOURCE_DIR}/include)
# 添加链接库
target_link_libraries(hello_test gtest gtest_main)
# 添加测试
add_test(NAME hello_test COMMAND hello_test)
在这个文件中,我们首先设置了测试文件的名称和源文件,并添加了头文件路径和链接库。然后,我们添加了一个测试,该测试的名称为 hello_test,执行命令为 hello_test。
编写测试用例
在 test 目录下创建 hello_test.cpp 文件,添加如下内容:
#include <gtest/gtest.h>
#include "hello.h"
TEST(HelloTest, OutputTest) {
EXPECT_EQ("Hello, world!", getHello());
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
在上面的代码中,我们编写了一个名为 OutputTest 的测试用例,使用 EXPECT_EQ 宏来判断 getHello() 函数返回的结果是否为 "Hello, world!"。然后,我们在 main 函数中调用 InitGoogleTest 函数来初始化 Google Test 框架,并使用 RUN_ALL_TESTS 函数来运行所有的测试用例。
在项目的根目录下执行如下命令:
mkdir build
cd build
cmake ..
这些命令会在 build 目录下生成 Makefile 文件,并编