GoogleTest

    Then, in your main :

    1. option(PACKAGE_TESTS "Build the tests" ON)
    2. if(PACKAGE_TESTS)
    3. enable_testing()
    4. include(GoogleTest)
    5. add_subdirectory(tests)
    6. endif()

    I would recommend using something like PROJECT_NAME STREQUAL CMAKE_PROJECT_NAME to set the default for the PACKAGE_TESTS option, since this should only build by default if this is the current project. As mentioned before, you have to do the enable_testing in your main CMakeLists.

    Now, in your tests directory:

    1. add_subdirectory("${PROJECT_SOURCE_DIR}/extern/googletest" "extern/googletest")

    The next line is optional, but keeps your CACHE cleaner:

    If you are interested in keeping IDEs that support folders clean, I would also add these lines:

    1. set_target_properties(gtest PROPERTIES FOLDER extern)
    2. set_target_properties(gtest_main PROPERTIES FOLDER extern)
    3. set_target_properties(gmock PROPERTIES FOLDER extern)

    Then, to add a test, I’d recommend the following macro:

    1. # create an exectuable in which the tests will be stored
    2. add_executable(${TESTNAME} ${ARGN})
    3. # link the Google test infrastructure, mocking library, and a default main fuction to
    4. # the test executable. Remove g_test_main if writing your own main function.
    5. target_link_libraries(${TESTNAME} gtest gmock gtest_main)
    6. # gtest_discover_tests replaces gtest_add_tests,
    7. # see https://cmake.org/cmake/help/v3.10/module/GoogleTest.html for more options to pass to it
    8. gtest_discover_tests(${TESTNAME}
    9. # set a working directory so your project root so that you can find test data via paths relative to the project root
    10. WORKING_DIRECTORY ${PROJECT_DIR}
    11. PROPERTIES VS_DEBUGGER_WORKING_DIRECTORY "${PROJECT_DIR}"
    12. )
    13. endmacro()
    14. package_add_test(test1 test1.cpp)

    You can use the downloader in my CMake helper repository, using CMake’s include command.

    This is a downloader for , based on the excellent DownloadProject tool. Downloading a copy for each project is the recommended way to use GoogleTest (so much so, in fact, that they have disabled the automatic CMake install target), so this respects that design decision. This method downloads the project at configure time, so that IDEs correctly find the libraries. Using it is simple:

    1. cmake_minimum_required(VERSION 3.10)
    2. project(MyProject CXX)
    3. list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
    4. enable_testing() # Must be in main file
    5. include(AddGoogleTest) # Could be in /tests/CMakeLists.txt
    6. add_executable(SimpleTest SimpleTest.cu)
    7. add_gtest(SimpleTest)

    [^1]: Here I’ve assumed that you are working on a GitHub repository by using the relative path to googletest.