Skip to content

GoogleTest: Add new DISCOVERY_MODE option to gtest_discover_tests

Introducing a new DISCOVERY_MODE mode option, which provides greater control over when gtest_discover_tests performs test discovery.

It has two supported modes:

  • POST_BUILD
  • PRE_TEST

POST_BUILD is the default behavior, which adds a POST_BUILD command to perform test discovery after the test has been built.

PRE_TEST is a new mode, which delays test discovery until test execution.

DISCOVERY_MODE can be controlled in two ways:

  1. Setting the DISCOVERY_MODE when calling gtest_discover_tests
  2. Setting the global CMAKE_GTEST_DISCOVER_TESTS_DISCOVERY_MODE prior to calling gtest_discover_tests

By delaying test discovery until ctest runtime, we can provide better cross compile support, because we're more likely to be in an environment that can run the test executable.

This was achieved by moving the command for test discovery into the generated ctest include file.

In PRE_TEST mode, the generated include file now has the form:

if(EXISTS "path/to/test.exe")
  if("path/to/test.exe" IS_NEWER_THAN "path/to/ctest_file")
    // command to discover tests
    // and generate ctest_file
  endif()
  include("path/to/ctest_file")
endif()
elseif()
  // test not built
endif()

Which generates the appropriate CTest files at runtime and regenerates the CTest files when the executable is updated.

In the old approach, test discovery was added as POST_BUILD step and the executable was ran in order to scan for tests.

If the test executable failed to run for any reason, this resulted in a link failure.

This failure could more commonly occur when cross compiling, because your build environment might not have the appropriate runtime environment dlls required to run the test executable.

I also ran into the issue when compiling a Qt application using Qt Creator. Qt Creator manages its build and runtime environments separately and only adds the Qt dlls to the environment during runtime -- not during build.

So when gtest_discover_tests ran my test executable, it promptly crashed because the environment wasn't correct, which resulted in a build failure.

Setting the DISCOVERY_MODE to PRE_TEST fixed my build failure by delaying test discovery until runtime, because this allowed the test exe to run in the proper environment.

Edited by Brad King

Merge request reports