Driving Boost.Test with CMake02 Jun 2015
Boost.Test is one of the more popular C++ based test frameworks on the market. With it being a boost library, chances are its already installed in the local environment, or can be easily built. This article doesn’t aim to show how to use Boost.Test. Rather, it shows how to incorporate building and running those tests with CMake, one of the most popular build systems for C++ projects. This article assumes that a CMake based project already exists.
To begin, Boost.Test must be included in the project.
Next, create a text file called BoostTestHelpers.cmake. This file will house a CMake helper function, add_boost_test which will be used to generate a test runner usable by CTest from a single test source file. This function takes a single source file containing Boost.Test unit tests and optionally a library dependency to link against. In cases where the library being tested is header-only, the dependency parameter is not required. In this file, create a skeleton of the add_boost_test function.
This function takes the base name of the given source file and uses it as the executable name of test runner. For example, if SomeUnitTests.cpp is passed to the add_boost_test function, then the test runner executable will be named SomeUnitTests. Then the executable is added and linked to the library being tested, if it’s not a header-only library, and the Boost.Test library.
By default, the CTest runner executes and reports on the tests being run at the executable level. This means if the example SomeUnitTests.cpp file contains 50 tests, CTest only reports whether the entire file passes or fails. An example is shown here.
While of some use, it would be more useful if CTest reported the names of each test it runs. To accomplish this objective, the test file is read and a regex used to search for all Boost.Test test cases and scrape the names. The tests names are stored in the array FOUND_TESTS where they can be used to add the individual tests.
Finally, a loop is performed over all of the found tests. Any excess characters are stripped from the test name and then finally the test is registered with CTest.
Adding the tests to CMake in this manner will generate more informative test output. For example, if SomeUnitTests.cpp contains three tests labeled Test1, Test2, and Test3, the output from tests added via add_boost_test will look similar to the following.
The final product is a simple CMake function that can be called as simply as follows, where SomeUnitTests.cpp is a file containing Boost.Test unit tests and my_library is the library containing the code being tested.
Below is the completed add_boost_test helper function. Additional improvements would be to support an arbitrary number of dependency libraries, however, the function as is can be a useful tool for easily incorporating Boost.Test unit tests into a CMake build environment.