cmakectest

CMake & CTest: How do I modify 'make' to only build and 'make test' to build and run tests?


How can I build AND run my tests with make test?

Currently, make builds all of my tests, and make test runs them. I'd like for make to only build the project without the tests, and make test to build and run the tests.

Top level CMakeLists.txt:

# Build tests
    mark_as_advanced( BUILD_TESTS )
    set( BUILD_TESTS true CACHE BOOL "Tests build target available if true" )
    if( BUILD_TESTS )
        enable_testing()
        add_subdirectory( tests )
    endif()

tests/CMakeLists.txt

foreach( APP ${TESTAPPS} )
 add_executable( "${APP}" "${APP}.c" ${src_files})
 add_test( NAME "${APP}_test" COMMAND "${APP}" )
endforeach( APP ${TESTAPPS} )

Solution

  • add_executable(... EXCLUDE_FROM_ALL
    

    to exclude building from 'all'. make runs make all.

    Then follow https://stackoverflow.com/a/15060921/9072753 :

    add_custom_target(build_and_test ${CMAKE_CTEST_COMMAND} -V)
    add_dependencies(build_and_test "${APP}")
    add_test(....)