是什么 ? | : | an extension of gcov, a command-line tool which provides information about what parts of a program are actually executed (i.e. "covered") while running a particular test case. |
开发语言 | : | perl |
官方主页 | : | http://ltp.sourceforge.net/coverage/lcov.php |
源码仓库 | : | https://github.com/linux-test-project/lcov |
操作系统 | 包管理器 | 仓库 | 安装命令 |
---|---|---|---|
All | vcpkg | official | vcpkg install lcov vcpkg install lcov:x64-osx vcpkg install lcov:x64-linux vcpkg install lcov:x64-windows |
Windows | Chocolatey | official | choco install -y lcov |
macOS | HomeBrew | official | brew install lcov |
GNU/Linux | HomeBrew | official | brew install lcov |
apt | official | sudo apt-get install -y lcov | |
CentOS | yum | sudo yum install -y lcov | |
dnf | sudo dnf install -y lcov | ||
openSUSE | zypper | sudo zypper install -y lcov | |
Alpine Linux | apk | official | sudo apk add lcov |
pacman | official | sudo pacman -Syyu --noconfirm | |
Gentoo Linux | Portage | official | sudo emerge lcov |
需求:编写一个四则运算
中的加法运算
的实现,使用CUnit进行单元测试,使用lcov
生成测试覆盖率统计报告
。
设计:工程结构如下
add
└── src
├── include
│ └── add.h
├── lib
│ └── add.c
└── test
└── add.c
1、编写src/include/add.h
#ifndef ADD_H
#define ADD_H
int add(int a, int b);
#endif
2、编写src/lib/add.c
#include <add.h>
int add(int a, int b) {
return a + b;
}
3、编写src/test/add.c
#include <CUnit/CUnit.h>
#include <CUnit/Basic.h>
#include <add.h>
void test_add() {
CU_ASSERT_EQUAL(add(0, 0), 0);
CU_ASSERT_EQUAL(add(0, 1), 1);
CU_ASSERT_EQUAL(add(1, 0), 1);
CU_ASSERT_EQUAL(add(1, -1), 0);
}
// http://cunit.sourceforge.net/example.html
int main() {
/* initialize the CUnit test registry */
if (CUE_SUCCESS != CU_initialize_registry()) {
return CU_get_error();
}
/* add a suite to the registry */
CU_pSuite pSuite = CU_add_suite("Suite_1", NULL, NULL);
if (NULL == pSuite) goto cleanup;
/* add the tests to the suite */
if (NULL == CU_add_test(pSuite, "test add()", test_add)) goto cleanup;
CU_basic_set_mode(CU_BRM_VERBOSE);
CU_basic_run_tests();
cleanup:
CU_cleanup_registry();
return CU_get_error();
}
4、使用cc命令编译单元测试程序
cc -o add-test --coverage -Isrc/include -lcunit src/test/add.c src/lib/add.c
5、运行单元测试程序
./add-test
*.gcda
文件。每一个.c
源文件对应生成一个*.gcda
文件。6、生成测试覆盖率统计数据
lcov -c -o test.info -d .
7、生成HTML格式的统计报告
genhtml test.info -o output/
8、查看output
目录中的内容
9、在Web浏览器
中打开output/index.html