快速入门:使用 CMake 构建
设置项目
CMake 使用名为 CMakeLists.txt
的文件来配置项目的构建系统。您将使用此文件来设置项目并声明对 GoogleTest 的依赖。
接下来,您将创建 CMakeLists.txt
文件并声明对 GoogleTest 的依赖。在 CMake 生态系统中有多种表达依赖关系的方式;在本快速入门中,您将使用 CMake 的 FetchContent
模块。为此,在您的项目目录(my_project
)中创建一个名为 CMakeLists.txt
的文件,内容如下:
cmake_minimum_required(VERSION 3.14)
project(my_project)
# GoogleTest 至少需要 C++14
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(FetchContent)
FetchContent_Declare(
googletest
URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)
# 对于 Windows:防止覆盖父项目的编译器/链接器设置
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
FetchContent_MakeAvailable(googletest)
上述配置声明了对 GoogleTest 的依赖,并从 GitHub 下载。在上面的示例中,03597a01ee50ed33e9dfd640b249b4be3799d395
是要使用的 GoogleTest 版本的 Git 提交哈希;我们建议经常更新此哈希以指向最新版本。
如果使用本地的 gtest 源码,可以使用如下内容:
if(USE_SYSTEM_GTEST)
find_package(GTest)
if (NOT GTEST_FOUND)
message(FATAL_ERROR "system googletest was requested but not found")
endif()
else()
add_subdirectory(
"${CMAKE_CURRENT_SOURCE_DIR}/gtest-1.11.0"
# "${CMAKE_CURRENT_BINARY_DIR}/prefix"
)
# include_directories(SYSTEM "${CMAKE_CURRENT_SOURCE_DIR}/gtest-1.11.0/googletest/include")
endif()
创建并运行二进制文件
声明了对 GoogleTest 的依赖后,您可以在自己的项目中使用 GoogleTest 代码。
例如,在您的 my_project
目录中创建一个名为 hello_test.cc
的文件,内容如下:
#include <gtest/gtest.h>
// 演示一些基本断言。
TEST(HelloTest, BasicAssertions) {
// 期望两个字符串不相等。
EXPECT_STRNE("hello", "world");
// 期望相等。
EXPECT_EQ(7 * 6, 42);
}
GoogleTest 提供了 断言,您可以使用它们来测试代码的行为。上面的示例包含了 GoogleTest 的主要头文件,并演示了一些基本断言。
要构建代码,请将以下内容添加到 CMakeLists.txt
文件的末尾:
enable_testing()
add_executable(
hello_test
hello_test.cc
)
target_link_libraries(
hello_test
GTest::gtest_main
)
include(GoogleTest)
gtest_discover_tests(hello_test)
上述配置启用了 CMake 中的测试,声明了要构建的 C++ 测试二进制文件(hello_test
),并将其链接到 GoogleTest(gtest_main
)。最后两行启用了 CMake 的测试运行器,以发现二进制文件中包含的测试,使用了 GoogleTest CMake 模块。
现在您可以构建并运行测试:
my_project$ cmake -S . -B build -- The C compiler identification is GNU 10.2.1 -- The CXX compiler identification is GNU 10.2.1 ... -- Build files have been written to: .../my_project/build my_project$ cmake --build build Scanning dependencies of target gtest ... [100%] Built target gmock_main my_project$ cd build && ctest Test project .../my_project/build Start 1: HelloTest.BasicAssertions 1/1 Test #1: HelloTest.BasicAssertions ........ Passed 0.00 sec 100% tests passed, 0 tests failed out of 1 Total Test time (real) = 0.01 sec
恭喜!您已成功使用 GoogleTest 构建并运行了一个测试二进制文件。