首页 > 解决方案 > CLion:在构建之前运行测试

问题描述

我在 CLion (C++ + CMake) 中创建了一个项目,其中我有一个具有2 个配置的共享库项目 释放。我还为单元测试实施了谷歌测试。

当配置为Release时,我想在构建之前运行一些测试(或全部)。当测试失败时,不应构建库。

这可能吗?如果有怎么办?

标签: cmakeautomated-testsgoogletestclionjetbrains-ide

解决方案


我找到了答案add_custom_command()。在我的主要CMakeLists.txt我有

if(${CMAKE_BUILD_TYPE} STREQUAL "Release")
   #Rebuild the tests just in case some tests has changed and the executable was not rebuild
   add_custom_command(TARGET ${PROJECT_NAME} PRE_BUILD
           COMMAND ${CMAKE_COMMAND} --build "${CMAKE_BINARY_DIR}" --target tests --
           )

   if(${WIN32})
      set(TESTS_BIN tests.exe)
   else()
      set(TESTS_BIN tests)
   endif()
   #Run the tests executable
   add_custom_command(TARGET ${PROJECT_NAME} PRE_BUILD
           COMMAND "${CMAKE_BINARY_DIR}/${TESTS_BIN}"
           )
endif()

因此add_custom_command(),当测试可执行文件不返回 0(所有测试都已成功通过)时,构建将失败并且库将不会被构建。


推荐阅读