What does enable_testing() do in cmake?

余生长醉 提交于 2020-07-31 07:15:36

问题


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.


回答1:


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)



回答2:


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



来源:https://stackoverflow.com/questions/50468620/what-does-enable-testing-do-in-cmake

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!