我有一个CMake项目,我正在尝试启用代码覆盖(使用Gcov,Lcov和Geninfo)。为了做到这一点,我使用模块CodeCoverage.cmake为我的目标设置它。以下是设置此内容的代码。
if (ENABLE_COVERAGE AND NOT CMAKE_CONFIGURATION_TYPES)
if (NOT BUILD_TESTS)
set(BUILD_TESTS On CACHE STRING "" FORCE)
endif (NOT BUILD_TESTS)
include(CodeCoverage)
include_directories(include ${PROJECT_BINARY_DIR})
add_subdirectory(src) # <--
# Defines target Project-Name-lib, which is a
# library consisting of all sources files except main.cpp
# Also defines Project-Name, which is the executable
target_compile_options(Project-Name-lib PRIVATE "--coverage")
# Only add coverage flags to the library, _NOTHING_ else
SETUP_TARGET_FOR_COVERAGE(NAME coverage
EXECUTABLE tests
DEPENDENCIES coverage)
# Function from the module to enable coverage
else (ENABLE_COVERAGE AND NOT CMAKE_CONFIGURATION_TYPES)
# ... Normal build ...
endif (ENABLE_COVERAGE AND NOT CMAKE_CONFIGURATION_TYPES)
if (BUILD_TESTS)
include(CTest)
enable_testing()
add_subdirectory(tests)
endif (BUILD_TESTS)
这种方法非常有效,当我使用make coverage
运行我的程序时,报告会成功生成并可以在浏览器中查看。但是,有一个问题。 此方法仅启用库的覆盖,而不是我正在使用的任何本地头文件。例如,如果我有如下所示的标题:
class HelloWorld
{
public:
HelloWorld();
std::string hello() const; // <-- Implementation in header.cpp
std::string world() const; // <-- Implementation in header.cpp
int generateRandomNumber() const; // <-- Implementation in header.cpp
int headerFunction(int test) const
{
if (test == 45)
return 45;
else
return 4;
}
private:
std::string hello_;
std::string world_;
};
相应的测试用例(Using Catch 2.2.1):
SECTION("function headerFunction()")
{
REQUIRE(helloWorld.headerFunction(33) == 4);
// All branches are NOT covered
}
然后所有测试用例都通过(如预期的那样),但是头文件中的函数不会显示在index.html
中。只有header.cpp
中定义的函数才有。因此,我的代码覆盖率错误地显示为100%。 我应该如何更改我的CMake代码,以便头文件中定义的函数也包含在覆盖率报告中?