CMake and Test Suites
20 Jun 2015The FindGTest
module that ships with CMake provides the command GTEST_ADD_TESTS
that
registers all the test cases from a test executable with CMake so they are
listed individually in the report generated by CTest. The following
snippet shows its use:
As we see, the GTEST_ADD_TESTS
command receives the list of source files.
Starting from CMake version 3.1, we can also pass AUTO
instead of a list of
sources which tells GTEST_ADD_TESTS
to retrieve the list of source files from
the SOURCES
target property. Either way, it then analyzes the source code with
some regular expressions to find all the test cases.
This approach is problematic. Whenever we add or remove test cases, CMake needs to rerun. This approach also fails to find test cases where the header spans two lines …
… and it wrongly finds test cases in comments and inactive #if
sections:
Why are the sources parsed at all? The list of test cases can be easily retrieved from the compiled test executable via the command line. Instead of parsing the source code, we could parse the output:
Putting the above snippet of CMake code into our CMakeLists.txt file requires the test executable to be available at configure time. Of course, that does not make any sense at all. No, we want this code to be in the CTestTestfile.cmake file!
What we need is a CMake command that writes the above block of code and we pass it just the options that are specific to the test framework in use.
Such a command might be used for GTest:
And for Catch:
And for GLib Test:
And for Qt Test:
And a sad running joke: For Boost.Test it would be possible to, but only with the version on trunk.