Saturday, April 17, 2021

Setup Unit Test and Code Coverage for C++ in Linux

Setup Unit Test

  1. Clone Google Test repo https://github.com/google/googletest
  2. Checkout latest release tag (Optional)
  3. Install the gtest library with the following commands:
    a. mkdir build
    b. cd build
    c. cmake ..
    d. sudo make install

Setup Code Coverage

  1. Get lcov source code tar bar from http://ltp.sourceforge.net/coverage/lcov.php
  2. Extract lcov tar ball
  3. Execute  sudo make install 

Implementation

At the beginning of "CMakeLists.txt", include the "test" option to allow test running to be optional.
option(test "Build and tests." OFF) # Makes boolean 'test' available.

In addition, at the end of "CMakeLists.txt", include the following.  Add more files under "add_executable" to include more unit tests.
if (test)
    enable_testing()

    add_executable(runUnitTests
        main_test.cpp)

    target_link_libraries(runUnitTests -pthread
        gtest gtest_main
        gcov
        )

    target_compile_options(runUnitTests PRIVATE
        -std=c++11
        -Wall
        -fprofile-arcs
        -ftest-coverage
        )

    add_test(NAME unittest COMMAND runUnitTests)
endif()

The following should be included in "main_test.cpp":

#include <gtest/gtest.h>

int main(int argc, char *argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}


Running Unit Test and Generate Code Coverage Report


./runUnitTests --gtest_output="xml:gtest.xml"
gcov main_test.cpp.gcno
lcov --capture --directory . --output-file LCOVOUTPUT.info
genhtml LCOVOUTPUT.info --output-directory ./code_coverage