1

I am trying to implement a small example on how to use google test and lcov so I can see how my testing of the code is doing. Here is my example repository.

My project has the following file tree:

unit_test_coverage/
  |--CMakeLists.txt
  |--.gitignore
  |--src/
       |--CMakeLists.txt
       |--foo.h
       |--foo.cpp
       |--test/
            |--CMakeLists.txt
            |--unit_test.cpp

The library is just one class with two methods and a member:

foo.h

#ifndef FOO_H_
#define FOO_H_

class Foo
{
public:
  Foo(const double& value);

  double times(const double& value) const;

  bool isPositive() const;

private:
  double m_value;
};

#endif  // FOO_H_

foo.cpp

#include "foo.h"

Foo::Foo(const double& value) : m_value(value){};

double Foo::times(const double& value) const
{
  return m_value * value;
}

bool Foo::isPositive() const
{
  return m_value > 0;
}

and the unit test only tests one of the methods of the class:

unit_test.cpp

#include "gtest/gtest.h"

#include "../foo.h"

TEST(Foo, times)
{
  EXPECT_EQ(Foo(4).times(4), 16);
}

In the CMakeLists.txt of the root folder, I have added a custom target to run the test and generate the coverage report:

add_custom_target(run_tests
  COMMAND ${CMAKE_BIN}/unit_test
  COMMAND lcov --capture --directory ${CMAKE_SOURCE_DIR} --output-file gtest_demo.info --test-name gtest_demo --no-external
  COMMAND genhtml gtest_demo.info --output-directory ${CMAKE_SOURCE_DIR}/coverage_report --title "Code coverage report" --show-details --legend
)

When I run make run_tests a coverage report is generated: enter image description here

enter image description here

However, the report does not include the coverage of the files foo.h and foo.cpp, which is the opposite of what I want, as I want to check whether or not the Foo class is properly tested and covered. How can I incorporate the coverage of the class Foo (files foo.h and foo.cpp)?

apalomer
  • 1,895
  • 14
  • 36
  • 1
    You add profile options only for the test: https://github.com/apalomer/unit_test_coverage/blob/master/src/test/CMakeLists.txt#L47. What else do you expect? – Tsyvarev Jan 20 '21 at 11:24
  • My bad, I did not read the documentation, which makes it crystal clear that the effect of [`add_compile_options`](https://cmake.org/cmake/help/latest/command/add_compile_options.html) only affectes the current directory and childs, but not parents. – apalomer Jan 20 '21 at 11:33
  • [OT]: for `EXPECT_EQ`, it is expected first normally (so error message is correct in case of failure). – Jarod42 Jan 20 '21 at 11:35
  • @Jarod42 I don't understand your comment. Can you explain it a bit better? I guess I am doing something wrong but cannot figure out what! Thanks!! – apalomer Jan 20 '21 at 11:41
  • 1
    I meant it should be: `EXPECT_EQ(16, Foo(4).times(4));`. Not a big deal with wrong order, just the error message (for failed test) which might be a little "confusing". – Jarod42 Jan 20 '21 at 11:48

0 Answers0