0

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} )

1 Answers1

1
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(....)
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • 1
    So with this solution I would actually build and run my tests with `make build_and_test` or whatever I choose the target name to be. It cannot be just `make test`? – agustinvaca May 30 '23 at 20:04
  • `It cannot be just make test?` Yes. But I do not remember what happens when you do `add_custom_target(test`. Overall, you should be using `cmake --build` and `ctest` commands, not `make`. – KamilCuk May 30 '23 at 20:11
  • 1
    This may happen: [CMake error target "test" is reserved or not valid](https://stackoverflow.com/questions/46638704/cmake-error-target-name-test-is-reserved-or-not-valid). You can use "tests" though :) – Friedrich May 30 '23 at 20:28
  • I ended up following https://stackoverflow.com/a/56448477/14837560. Thank you this worked great! – agustinvaca May 31 '23 at 22:52