使用 lcov+gtest 的代码覆盖率只报告单元测试 cpp 文件的覆盖率,而不是被测库的文件

时间:2021-01-20 10:55:47

标签: c++ cmake lcov

我正在尝试实现一个关于如何使用 google test 和 lcov 的小例子,以便我可以看到我对代码的测试是如何进行的。 Here 是我的示例存储库。

我的项目有以下文件树:

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

该库只是一个具有两个方法和一个成员的类:

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;
}

并且单元测试只测试类的方法之一:

unit_test.cpp

#include "gtest/gtest.h"

#include "../foo.h"

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

在根文件夹的 CMakeLists.txt 中,我添加了一个自定义目标来运行测试并生成覆盖率报告:

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
)

当我运行 make run_tests 时,会生成一个覆盖率报告: enter image description here

enter image description here

然而,报告没有包括文件 foo.hfoo.cpp 的覆盖范围,这与我想要的相反,因为我想检查 Foo类经过适当的测试和覆盖。如何合并 Foo 类(文件 foo.hfoo.cpp)的覆盖范围?

0 个答案:

没有答案
相关问题