Search code examples
c++googletest

Setting up GoogleTest to run all tests in one executable


In setting up my most recent project I am attempting to use GoogleTest. Currently I have this:

macro(add_test_l TEST_NAME)

    # Create the executable and use the last arguments as source files.
    add_executable(${TEST_NAME} ${ARGN})

    # Link in the AMR and gtest libraries.
    target_link_libraries(${TEST_NAME}
        ${PROJECT_NAME}
        gtest
        gmock
        gtest_main
    )

    # Add the test to gtest.
    add_test(
        NAME ${TEST_NAME}
        COMMAND ${TEST_NAME}
    )

    list(APPEND TEST_SOURCE_FILES ${ARGN})

endmacro()

Then I can add my tests like add_test_l(Element Sets/Element.test.cpp) which is working and convenient. But this of course creates an executable for each test, which is not a bad thing as it allows for quick testing of a single file.

Though I do want the ability to run all the tests with a single exe (that way CI will be easier) so I have that list at the end of my macro and after adding all my individual tests I have:

add_executable(all_tests ${TEST_SOURCE_FILES})
target_link_libraries(all_tests
    ${PROJECT_NAME}
    gtest
    gmock
    gtest_main
)

Which creates an EXE to run all my test cases.

This does not seem efficient as I compile all my files twice. Is there a better way for me to achieve the desired outcome? Perhaps I can just add an option to enable / disable individual vs all tests exes.


Solution

  • It is unnecessary to have an executable per each file. Build one executable for all tests and learn the gtest option --gtest_filter. You can run each test individually:

    all_tests --gtest_filter=Element.Test
    

    Or you can run all Element tests like the macro add_test_l does it:

    all_tests --gtest_filter=Element.*
    

    More info about command line options is available:

    all_tests --help
    

    One of the useful commands:

    all_tests --gtest_list_tests