CLion:运行 构建前测试

CLion: run tests before build

我在 CLion (C++ + CMake) 中创建了一个项目,其中我有一个 共享库 项目,具有 2 个配置 Debug |发布。我还为单元测试实施了 google 测试。

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

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

我已经找到 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() 很聪明,因此当 tests 可执行文件不是 return 0(所有测试都已成功通过)时,构建将失败并且不会构建库。