这个答案与@romblen 的答案相同,但有点过时,所以我将分享我的解决方案。这是我所做的:
- 创建了一个玩具项目
(base) ciaran@DESKTOP-K0APGUV:/mnt/d/CoverageTest$ tree -L 2
.
├── CMakeLists.txt
├── cmake
│ └── CodeCoverage.cmake
├── src
│ ├── domath.cpp
│ ├── domath.h
│ └── testdomath.cpp
└── third_party
└── googletest
在哪里
// src/domath.h
#ifndef COVERAGETEST_DOMATH_H
#define COVERAGETEST_DOMATH_H
class domath {
public:
int add(int a, int b);
};
#endif //COVERAGETEST_DOMATH_H
和
// src/domath.cpp
#include "domath.h"
int domath::add(int a, int b) {
return a + b;
}
和
// src/testdomath.cpp
#include "gtest/gtest.h"
#include "domath.h"
TEST(DoMathTests, testAdd){
domath m;
int actual = m.add(4, 6);
ASSERT_EQ(10, actual);
}
- 下载 googletest 并将其放在第三方目录下
- 将这个线程上其他答案所分享的要点复制到
cmake/CodeCoverage.cmake
- 安装
gcovr
. 此步骤至关重要,因为此线程上的其他答案不再适用于gcovr
我已经拥有的版本:
(base) ciaran@DESKTOP-K0APGUV:/mnt/d/CoverageTest$ pip install gcovr
(base) ciaran@DESKTOP-K0APGUV:/mnt/d/CoverageTest$ gcovr --version
gcovr 4.2
(base) ciaran@DESKTOP-K0APGUV:/mnt/d/CoverageTest$ which gcovr
/home/ciaran/miniconda3/bin/gcovr
注意,我们需要gcovr
cmake 脚本的输出。4) 编写一个创建库、测试可执行文件并使用CodeCoverage.cmake
模块的 cmake 脚本:
cmake_minimum_required(VERSION 3.15)
project(CoverageTest)
set(CMAKE_CXX_STANDARD 14)
# setup googletest
add_subdirectory(third_party/googletest)
# create our library
add_library(DoMath STATIC src/domath.h src/domath.cpp)
add_dependencies(DoMath gtest gtest_main)
# create the test executable
add_executable(TestDoMath src/testdomath.cpp)
target_include_directories(TestDoMath PRIVATE third_party/googletest/googletest)
target_link_libraries(TestDoMath PRIVATE
DoMath gtest gtest_main)
add_dependencies(TestDoMath DoMath gtest gtest_main)
# now for coverage bits
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
if (CMAKE_COMPILER_IS_GNUCXX)
include(CodeCoverage)
append_coverage_compiler_flags()
# we need to turn off optimization for non-skewed coverage reports
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -O0")
# optional excludes - None needed here
# set(COVERAGE_EXCLUDES)
# importantly, set the path to the gcovr executable that you downladed
set(GCOVR_PATH "/home/ciaran/miniconda3/bin/gcovr")
# Works
setup_target_for_coverage_gcovr_xml(
NAME TestDoMathCoverageXml
EXECUTABLE TestDoMath
DEPENDENCIES TestDoMath DoMath
)
# Works
setup_target_for_coverage_gcovr_html(
NAME TestDoMathCoverageHtml
EXECUTABLE TestDoMath
DEPENDENCIES TestDoMath DoMath
)
# This one did not work for me:
setup_target_for_coverage_lcov(
NAME TestDoMathCoverageLcov
EXECUTABLE TestDoMath
DEPENDENCIES TestDoMath DoMath
)
endif ()
就是这样。现在只需构建新目标。
祝你好运。