1

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)
lighthouse
  • 413
  • 2
  • 10

2 Answers2

1

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.

Greg Kramida
  • 4,064
  • 5
  • 30
  • 46
0

You could just write a command in the syntax of your shell that runs testing after build and then use your shell's history features to make it easier to re-run the command. You could even wrap the command in a shell alias or shell script. Ex. in Bash: cmake --build <build dir> <other args> && ctest <args>.

There's also ctest --build-and-run ....

starball
  • 20,030
  • 7
  • 43
  • 238