G单元测试(三)

181 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情

在单元测试(一)中主要介绍了Go的原生单元测试API的使用技巧

在单元测试(二)中主要介绍了Go单元测试常见的参数的使用

本文将介绍GO关于测试覆盖率报告的生成

测试覆盖率

查看测试覆盖率 -cover

运行示例:go test -cover 当前的测试覆盖率为35%,测试用例不能完全测试代码

go test -cover             

PASS
coverage: 35.0% of statements
ok      gotest  3.428s

导出测试覆盖率 -coverprofile

参数后直接携带导出的文件路径即可 比如导出到test.out 文件,执行命令后,程序会自动生成test.out文件

go test -coverprofile=test.out

test.out

mode: set
gotest/batchmark.go:3.44,5.28 2 0
gotest/batchmark.go:8.2,8.17 1 0
gotest/batchmark.go:5.28,7.3 1 0
gotest/batchmark.go:11.44,13.28 2 0
gotest/batchmark.go:16.2,16.17 1 0
gotest/batchmark.go:13.28,15.3 1 0
gotest/embed_first.go:16.28,18.2 1 1
gotest/embed_first.go:20.27,23.2 2 0
gotest/embed_first.go:25.16,27.26 2 0
gotest/embed_first.go:27.26,28.16 1 0
gotest/embed_first.go:28.17,30.4 0 0
gotest/example.go:5.17,7.2 1 1
gotest/example.go:9.19,12.2 2 1
gotest/example.go:14.16,22.32 2 1
gotest/example.go:22.32,24.3 1 1

通过测试覆盖率报告查看每个测试方法的测试覆盖率情况

运行示例go tool cover -func=test.out

go tool cover -func=test.out

gotest/batchmark.go:3:          MakeSliceWithoutAlloc   0.0%
gotest/batchmark.go:11:         MakeSliceWitPrevAlloc   0.0%
gotest/embed_first.go:16:       ReadHelloTxt            100.0%
gotest/embed_first.go:20:       ReadHelloFS             0.0%
gotest/embed_first.go:25:       ReadDir                 0.0%
gotest/example.go:5:            SayHello                100.0%
gotest/example.go:9:            SayGoodBye              100.0%
gotest/example.go:14:           SayName                 100.0%
total:                          (statements)            35.0%

生成html可视化覆盖率报告

运行示例go tool cover -html=test.out在浏览器中打开的测试报告示例如下:

测试覆盖率html报告

红色部分的代码是没有被覆盖到的测试代码,绿色部分是被覆盖到的测试代码。

利用三方库生成测试报告

go-test-report

生成炫酷的测试覆盖率报告

  1. 安装到本地
go install github.com/vakenbolt/go-test-report
  1. 生成测试报告
go test -json | go-test-report

相应的文件目录下回生成一个test_report.html浏览器打开后大概是这个样子

test_report.png