I do have some experience with rust and cargo. It's really convenient cargo running test at every build by default.
Is there anyway I can get similar behavior with CMake and Catch2 for C++ project? Here is my project structure, and CMakeLists.txt.
.
├── CMakeLists.txt
├── LICENSE
├── README.md
├── library.properties
├── src
│ ├── math.hpp
│ ├── prelude.hpp
│ ├── signal.hpp
│ └── sm.hpp
└── test
├── CMakeLists.txt
└── prelude_test.cpp
#./CMakeLists.txt
cmake_minimum_required(VERSION 3.11)
project(
efp
VERSION 0.1
LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED On)
find_package(Catch2 3 REQUIRED)
include(CTest)
include(Catch)
enable_testing()
add_library(efp INTERFACE)
target_include_directories(efp INTERFACE "./src")
add_subdirectory("./test")
#./test/CMakeLists.txt
add_executable(prelude_test prelude_test.cpp)
target_link_libraries(prelude_test
PRIVATE
Catch2::Catch2WithMain
efp)
catch_discover_tests(prelude_test)
You should be able to do this via add_custom_command in CMake like so:
add_custom_command(
TARGET prelude_test
COMMENT "Run tests"
POST_BUILD
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
COMMAND ${CMAKE_CTEST_COMMAND} -C $<CONFIGURATION> -R "^prelude_test$" --output-on-failures
)
On running make
or ninja
whatever your generator is set to, if the target rebuild is triggered (i.e. if you changed a source file), the test will be run automatically.
Source, with info on how to adapt this to multiple test targets: SO answer.