cover 转载

覆盖是指测试文件对函数的覆盖率是多少

命令

go test -cover

输出

PASS
coverage: 100.0% of statements
ok      awesomeProject/Search   0.120s

我们的覆盖率是100%,我们想看看具体的情况

命令

go test -coverprofile=coverage.out

上述命令会输出文件

读取命令

go tool cover -func=coverage.out

输出

awesomeProject/Search/Search.go:5:      BinarySearch1   100.0%
awesomeProject/Search/Search.go:13:     BinarySearch2   100.0%
total:                                  (statements)    100.0%

但是这个很不直观,我们可以用一个更清晰的HTML页面来显示结果:

命令

go tool cover -html=coverage.out

输出

html网页,其中绿色表示覆盖的,红色表示未覆盖的

更精细的控制

这种代码级别的覆盖测试工具还有其他作用。比如它不仅仅可以告诉你一条语句是否被执行了,还可以告诉你它执行了多少次。

go test 接受 -covermode参数,一共有三种设置:

  • set(默认):每条语句是否被执行了?
  • count:每条语句被执行了多少次?
  • atomic:和count相似,但是能够在并行程序中精确计数(使用了 sync/atomic 包)。

可以按照上述方式重新进行测试,可以看到在html界面中不同覆盖率的语句用不同的颜色表示出来了。

命令

go test -coverprofile=coverage.out --covermode=count

读取

go tool cover -html=coverage.out

输出

参考

统计 Golang 项目的测试覆盖率