Question

I have several .cpp files that contain tests for different classes and look like this:

#include <gtest/gtest.h>

namespace {
//lots of tests
}

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

and a CMakeLists.txt file that looks like this:

add_subdirectory(/usr/src/gtest gtest)
include_directories(${GTEST_INCLUDE_DIR})

add_executable(TestA TestA.cpp)
target_link_libraries(TestA
     gtest
)

add_executable(TestB TestB.cpp)
target_link_libraries(TestB
    gtest
)

add_executable(TestC TestC.cpp)
target_link_libraries(TestC
    gtest
)

I like this setup because it's handy to run just the tests for the component I am currently working on. Executing one Test file is obviously much faster than executing all of them. However, every now and then I want to run all tests. How can I achieve this easily within my setup?

Was it helpful?

Solution

You can use CTest (it's usually installed along with CMake) to achieve this.

First, you need to include the CTest module in your CMakeLists.txt, then you just need to use the add_test command for each of your test executables:

include(CTest)
add_subdirectory(/usr/src/gtest gtest)
include_directories(${GTEST_INCLUDE_DIR})

add_executable(TestA TestA.cpp)
target_link_libraries(TestA gtest)
add_test(NAME AllTestsInA COMMAND TestA)

add_executable(TestB TestB.cpp)
target_link_libraries(TestB gtest)
add_test(NAME AllTestsInB COMMAND TestB)

add_executable(TestC TestC.cpp)
target_link_libraries(TestC gtest)
add_test(NAME AllTestsInC COMMAND TestC)

Now, once your test exes are built, from your build folder you can execute CTest to run all the tests. E.g. to run the Debug tests:

ctest -C Debug

or to get more verbose output:

ctest -C Debug -V
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top