0
votes

I have been looking at examples of CMake to help me build my project with its test folder. The main issue is that I have to include all the test/.cpp* files in my test folder into tests/main.cpp for the tests to run. I think I should include my tests with the add_test call in my test/CMakeLists.txt. Below is my current CMakeLists file:

enable_testing()

find_package(GTest REQUIRED)

add_executable(test main.cpp)

target_include_directories(test PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../include)

target_link_libraries(test MainProjectLib ${GTEST_LIBRARIES})

And my main.cpp is the following.

#include "file_in_test1.cpp"
#include "file_in_test2.cpp"
#include <gtest/gtest.h>

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

I read some examples that use the standard CTest library for unit testing, but I am using Google Test. I would like to be able to run cmake, make, and then ./test to run all test methods found in file_in_test1.cpp and file_in_test2.cpp without having to directly import those files into test/main.cpp. What additions to CMakeLists.txt do I have to make?

1

1 Answers

0
votes

The one line you could add at the end would be:

gtest_discover_tests(test)

This is a replacement for gtest_add_tests since cmake version 3.10, and then after you build everything, you can just run ctest and it will give you a nice summary of the tests it just ran. You can read more about this option here.

Also, just as a note, it would probably be better to make individual test files for each of the tests you have, rather than including the .cpp files in your main test file.

What I generally do is define an option to allow for testing and a function that creates the test I need (see below):

option(build_all_tests "Build all unit tests in the test directory." OFF)

if (build_all_tests)
    include(CTest)
    include(GoogleTest)

    enable_testing()

    ## Function to create a new test based off the pre-defined naming template ##
    function(new_test testname interiorDirectory)
        add_executable(${testname} ${interiorDirectory}/${testname}.cpp)

        target_link_libraries(${testname} ${GTEST_LIBRARIES})

        gtest_discover_tests(${testname}
                        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${interiorDirectory})
    endfunction(new_test)

    ## Locate GTest ##
    find_package(GTest REQUIRED)
    include_directories(${GTEST_INCLUDE_DIRS})

    ## Create all tests ##
    new_test(test1 test/test1)
    new_test(test2 test/test2)
    ...
endif()