Reputation: 419
I see that to add my google tests(for my cpp project), I need to make a call to enable_testing() in the root source directory. Can someone explain what this really does? Also why would cmake not make this default?
This is all I could get from the documentation.
Enables testing for this directory and below. See also the add_test() command. Note that ctest expects to find a test file in the build directory root. Therefore, this command should be in the source directory root.
Upvotes: 40
Views: 26482
Reputation: 25317
When you call add_test(...)
, CMake will not generate the tests unless enable_testing()
has been called. Note that you usually don't need to call this directly. Just include(CTest)
and it will invoke it for you.
My CMake setup often looks like this:
include(CTest) # note: this adds a BUILD_TESTING which defaults to ON
# ...
if(BUILD_TESTING)
add_subdirectory(tests)
endif()
In the tests directory:
# setup test dependencies
# googletest has some code they explain on how to set it up; put that here
add_executable(MyUnitTests
# ...
)
target_link_libraries(MyUnitTests gtest_main)
add_test(MyUnitTestName MyUnitTests)
Upvotes: 35
Reputation: 28659
It sets a definition in the generator, CMAKE_TESTING_ENABLED
, which, if not defined, allows cmake to skip a lot of additional processing related to the registration of unit-tests with ctest. (example)
The major benefit of this is that it allows you to selectively enable/disable the generation of tests in your build files, when calling cmake.
As an example, you could put the following snippet in your root CMakeLists.txt file
:
It creates an option to enable tests, which are off by default.
option(ENABLE_TESTS "Enable tests" OFF)
if (${ENABLE_TESTS})
enable_testing()
endif()
You only need to do this once, in your root CMakeLists.txt
, and in the rest of your cmake files you can happily call add_test()
etc, without having to worry about checking if (${ENABLE_TESTS})
every time
Upvotes: 19