# gtest
Google 开源的 c++ 单元测试框架
https://google.github.io/googletest/
# 查看代码覆盖率
- GCC + gcov (cmake 一般带了) + lcov
- 修改 CMakeLists.txt
lcov1 2 3 4 5 6 7 8 9 10 11 12 13
| option(ENABLE_COVERAGE "Enable coverage build" OFF)
if(ENABLE_COVERAGE) if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") target_compile_options(your_library_or_source_files PRIVATE -O0 -g --coverage ) target_link_options(your_library_or_source_files PRIVATE --coverage) endif() endif()
|
- 构建并运行测试
…
cmake … -DENABLE_COVERAGE=ON
…
- 生成可视化覆盖率报告(HTML)
lcov1 2 3 4 5 6 7 8 9 10 11 12 13 14
| lcov --capture --initial --directory . --output-file coverage_base.info
lcov --capture --directory . --output-file coverage_test.info
lcov --add-tracefile coverage_base.info --add-tracefile coverage_test.info --output-file coverage_total.info
lcov --remove coverage_total.info '/usr/*' '*/thirdpart/*' '*/googletest*' --output-file coverage_final.info
genhtml coverage_final.info --output-directory coverage_report
|
或者直接
lcov
然后再 build 目录下的 coverage_html 目录下查看 index.html,可以点开具体文件查看哪些行没有覆盖到
# 如何提高单元测试的覆盖率
分析当前覆盖率报告,找出未执行的代码路径,然后编写新的测试用例来触发这些路径。