Generating test coverage for a framework

Over the last week I was trying to add unit tests to some rather old piece of code in frameworks. Of course I wanted to know how good this test is and looked into how one can generate test coverage for our tests. As I consider this as rather useful I thought to share the steps.

For generating the test coverage I used gcov which is part of gcc. So nothing to do there. As a frontend I decided for lcov as that can generate some nice html views. On debian based systems it is proved by package lcov.

Let’s assume that we have a standard framework with:

  • framework/autotests
  • framework/src
  • framework/tests

The first step to enable test coverage is to modify the CMakeLists.txt. There is the possibility to switch to CMAKE_BUILD_TYPE “Coverage”, but that would require building all of frameworks with it. Interesting for the CI system, but maybe not for just developing one unit test.

In your framework toplevel CMakeLists.txt add the following definition:

add_definitions(-fprofile-arcs -ftest-coverage)

And also adjust the linking of each of your targets:

target_link_libraries(targetName -fprofile-arcs -ftest-coverage)

Remember to not commit those changes 😉

Now recompile the framework, go the build directory of your framework and run:

make test

This generates the basic coverage data which you can now process with lcov run from your build directory:

lcov --capture --directory ./ --output-file coverage.info

And last step is to generate the html output:

genhtml coverage.info --output-directory /path/to/generated/pages

Open your favorite web browser and load index.html in the specified path and enjoy.

4 Replies to “Generating test coverage for a framework”

  1. > Remember to not commit those changes 😉

    We usually wrap the stuff in something like this

    string(TOLOWER “${CMAKE_BUILD_TYPE}” cmake_build_type_lower)
    if(cmake_build_type_lower MATCHES coverage)

    endif()

    So you can also commit it and only trigger it with cmake -DCMAKE_BUILD_TYPE=coverage

    1. as mentioned the build type already exists and does all adjustments automatically (it you carry such ifs, have a look to extra-cmake-modules)

Comments are closed.