31

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.

informativeguy
  • 329
  • 1
  • 3
  • 7

2 Answers2

30

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)
Justin
  • 24,288
  • 12
  • 92
  • 142
  • 1
    Since `include(CTest)` internally invokes `enable_testing()`, does it mean that it's no meaning to manually invoke `enable_testing()`? – John Oct 10 '22 at 02:03
14

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

Steve Lorimer
  • 27,059
  • 17
  • 118
  • 213