在 CMake 中实现项目编译后自动执行指定的单元测试目标,可以通过以下几种方式实现:
方法 1:使用 add_custom_command
和构建后事件
# 定义你的主目标
add_executable(my_app main.cpp)
# 定义测试目标
add_executable(my_tests test.cpp)
target_link_libraries(my_tests PRIVATE gtest_main)
# 添加构建后命令
add_custom_command(TARGET my_app POST_BUILD
COMMAND ${CMAKE_CTEST_COMMAND} -R "my_tests" --output-on-failure
COMMENT "Running unit tests after build..."
)
方法 2:使用 add_dependencies
确保测试在构建后运行
add_executable(my_app main.cpp)
add_executable(my_tests test.cpp)
# 创建一个伪目标
add_custom_target(run_tests ALL
COMMAND ${CMAKE_CTEST_COMMAND} -R "my_tests" --output-on-failure
DEPENDS my_tests
COMMENT "Running unit tests..."
)
# 确保主应用构建后运行测试
add_dependencies(run_tests my_app)
方法 3:使用 CMake 的测试属性和 CTest
# 定义测试
add_test(NAME my_tests COMMAND my_tests)
# 设置测试属性,使其在构建后运行
set_tests_properties(my_tests PROPERTIES
FIXTURES_REQUIRED "my_app"
RUN_SERIAL TRUE
)
方法 4:针对特定构建类型(如 Debug)自动运行测试
if(CMAKE_BUILD_TYPE STREQUAL "Debug")
add_custom_command(TARGET my_app POST_BUILD
COMMAND ${CMAKE_CTEST_COMMAND} -R "my_tests"
COMMENT "Auto-running tests in Debug build"
)
endif()
最佳实践建议:
-
选择性执行:结合
--gtest_filter
只运行关键测试COMMAND my_tests --gtest_filter=CriticalTests.*
-
错误处理:确保测试失败会中断构建
COMMAND ${CMAKE_COMMAND} -E env CTEST_OUTPUT_ON_FAILURE=1 ${CMAKE_CTEST_COMMAND} --stop-on-failure -R my_tests
-
条件控制:通过选项控制是否自动运行
option(AUTO_RUN_TESTS "Run tests automatically after build" ON) if(AUTO_RUN_TESTS) add_custom_command(...) endif()
-
跨平台兼容:使用 CMake 生成平台相关命令
if(WIN32) # Windows 特定命令 else() # Unix 特定命令 endif()
完整示例:
cmake_minimum_required(VERSION 3.12)
project(MyProject)
# 启用测试
enable_testing()
# 主应用程序
add_executable(my_app main.cpp)
# 测试程序
add_executable(my_tests test.cpp)
target_link_libraries(my_tests PRIVATE gtest_main)
# 注册测试
add_test(NAME my_tests COMMAND my_tests)
# 构建后自动运行测试
option(AUTO_RUN_TESTS "Run tests automatically after build" ON)
if(AUTO_RUN_TESTS)