我正在尝试实现一个关于如何使用 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
时,会生成一个覆盖率报告:
然而,报告没有包括文件 foo.h
和 foo.cpp
的覆盖范围,这与我想要的相反,因为我想检查 Foo
类经过适当的测试和覆盖。如何合并 Foo
类(文件 foo.h
和 foo.cpp
)的覆盖范围?