1 准备环境
操作系统 CentOS 8:
$ cat /etc/system-release
CentOS Linux release 8.0.1905 (Core)
从网站https://cpputest.github.io/下载cpputest-3.8.tar.gz
$ tar xvfz cpputest-3.8.tar.gz
$ cd cpputest-3.8
$ ./autogen.sh
$ ./configure
$ make
2 准备被测函数
$ cat code.cpp
int test_func ()
{
return 1;
}
3 准备测试代码
$ cat a.cpp
#include "CppUTest/TestHarness.h"
#include "CppUTest/CommandLineTestRunner.h"
int test_func ();
TEST_GROUP(FirstTestGroup)
{
};
TEST(FirstTestGroup, FirstTest)
{
int x = test_func();
CHECK_EQUAL(1, x);
}
int main(int ac, char** av)
{
return CommandLineTestRunner::RunAllTests(ac, av);
}
4 编译测试代码
$ g++ a.cpp code.cpp -lstdc++ -lCppUTest -I/home/louyang/cpputest/cpputest-3.8/include -L/home/louyang/cpputest/cpputest-3.8/lib
5 运行查看结果
$ ./a.out
.
OK (1 tests, 1 ran, 1 checks, 0 ignored, 0 filtered out, 0 ms)
$ ./a.out -r 3
Test run 1 of 3
.
OK (1 tests, 1 ran, 1 checks, 0 ignored, 0 filtered out, 0 ms)
Test run 2 of 3
.
OK (1 tests, 1 ran, 1 checks, 0 ignored, 0 filtered out, 0 ms)
Test run 3 of 3
.
OK (1 tests, 1 ran, 1 checks, 0 ignored, 0 filtered out, 0 ms)
看代码覆盖率的方法
$ g++ -fprofile-arcs -ftest-coverage a.cpp code.cpp -lstdc++ -lCppUTest -I/home/louyang/cpputest/cpputest-3.8/include -L/home/louyang/cpputest/cpputest-3.8/lib && ./a.out
.
OK (1 tests, 1 ran, 1 checks, 0 ignored, 0 filtered out, 0 ms)
查看代码覆盖率:
$ gcov code.cpp
File 'code.cpp'
Lines executed:100.00% of 2
Creating 'code.cpp.gcov'
查看代码及分支覆盖率:
$ gcov code.cpp -b
File 'code.cpp'
Lines executed:100.00% of 2
No branches
No calls
Creating 'code.cpp.gcov'
网友评论