Go 单元测试覆盖率计算方法和逻辑
1. 使用命令导出覆盖率文件明细列表
go test -coverprofile=coverage.out ./...
cat coverage.out
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1178.18,1180.13 2 0
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1184.23,1186.18 2 0
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1186.18,1188.13 2 0
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1192.46,1194.4 1 0
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1205.60,1208.16 3 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1213.2,1237.21 24 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1243.2,1306.17 4 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1208.16,1211.3 2 0
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1237.21,1239.3 1 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1239.8,1241.3 1 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1309.47,1323.48 11 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1323.48,1327.52 3 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1327.52,1330.18 3 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1334.4,1335.29 2 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1340.4,1341.37 2 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1355.4,1355.73 1 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1330.18,1332.5 1 0
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1335.29,1338.5 2 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1341.37,1342.40 1 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1353.5,1353.26 1 1
codeup.aliyun.com/xy/freebook-commerce/bookadv/cmd/service/adv_service.go:1342.40,1344.71 1 1
覆盖文件明细的格式如下
name.go:line.column,line.column numberOfStatements count
{文件名}:{代码块起点(行列)},{代码块终点(行列)} {有效代码行数} {是否覆盖}
2. 使用命令计算覆盖率
go tool cover -func=coverage.out
其原理很简单:覆盖有效代码行数
/ 有效代码总行数
也可使用 awk
计算大概如下
cat c.out | awk 'BEGIN {cov=0; stat=0;} \\
$3!="" { cov+=($3==1?$2:0); stat+=$2; } \\
END {printf("Total coverage: %.2f%% of statements\\n", (cov/stat)*100);}'
3. 准确性
值的注意的是,覆盖文件列表并不包含所有的文件,只包含单元测试执行过的 package 中的代码文件,并且不包含 struct 定义等语句块。
所以覆盖率 15.8%,并不是所有的代码