軟件名稱 | 軟件版本 |
---|---|
Linux操作系統(tǒng) | Ubuntu 22.04 LTS(X64) |
cmake | 3.22.1 |
CMake可以支持gtest測試用例此熬,具體方法可以參考這里,主要使用到的是include(GoogleTest)
和gtest_add_tests(TARGET <target>)
兩個命令。
gtest_add_tests命令中的<target>指的就是使用gtest框架編寫用例編譯出來的可執(zhí)行文件犀忱,可以多次使用gtest_add_tests命令添加不同的測試可執(zhí)行文件募谎,另外要使能測試功能,需要再頂層的CMakeLists.txt文件末尾增加enable_testing()
阴汇。
example/CMakeLists.txt文件內(nèi)容:
cmake_minimum_required(VERSION 3.22)
project(example)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/output) # 設置可執(zhí)行目標文件的輸出目錄
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/output) # 設置靜態(tài)庫文件的輸出目錄
add_subdirectory(src)
add_subdirectory(lib)
target_link_libraries(main mylib)
if (DEBUG)
target_compile_definitions(mylib PRIVATE DEBUG_INFO)
endif()
set(CMAKE_INSTALL_PREFIX /home/shengyi/install/my_test)
install(TARGETS main DESTINATION bin)
install(TARGETS mylib DESTINATION lib)
install(FILES lib/mylib.h DESTINATION include)
enable_testing()
example/src/CMakeLists.txt文件內(nèi)容:
FIND_PACKAGE(GTest
CONFIG REQUIRED
PATHS /home/shengyi/install/gtest/lib/cmake/GTest)
if (GTest_FOUND)
GET_PROPERTY(include_def TARGET GTest::gtest PROPERTY INTERFACE_INCLUDE_DIRECTORIES)
GET_PROPERTY(library_def TARGET GTest::gtest PROPERTY INTERFACE_LINK_LIBRARIES)
MESSAGE("Found gtest libs, include: ${include_def}, library: ${library_def}")
ADD_EXECUTABLE(main main.cpp)
TARGET_LINK_LIBRARIES(main GTest::gtest)
endif()
include(GoogleTest)
gtest_add_tests(TARGET main)
進入example/build
目錄執(zhí)行cmake ..
数冬、make test
后輸出如下:
$ make test
Running tests...
Test project /home/shengyi/code/gitee_repo/projects/cmake/example/build
Start 1: FirstTest.testcase1
1/1 Test #1: FirstTest.testcase1 .............. Passed 0.00 sec
100% tests passed, 0 tests failed out of 1
Total Test time (real) = 0.00 sec