工具
go get golang.org/x/tools/cmd/cover
go get github.com/mattn/goveralls
分析测试代码的覆盖率
1. 查看整体的覆盖率
cd 项目的根目录
go test -cover
PASS
coverage: 76.5% of statements
ok github.com/yezihack/gorestful 0.005s
2. 覆盖率分析
a. 生成覆盖率的分析文件
go test -coverprofile=coverage.out
b. 对文件进行分析
go tool cover -func=coverage.out
c. 生成html分析页面
没有被测试用例代码覆盖会标记为红色.
go tool cover -html=coverage.out -o coverage.html
3. 命令列表
Usage of 'go tool cover':
Given a coverage profile produced by 'go test': 生成覆盖率文件
go test -coverprofile=c.out
Open a web browser displaying annotated source code: 分析覆盖率文件,生成html文件
go tool cover -html=c.out
Write out an HTML file instead of launching a web browser: 分析覆盖率文件,生成html文件并指定生成路径 -o
go tool cover -html=c.out -o coverage.html
Display coverage percentages to stdout for each function: 分析覆盖率文件, 屏幕上直接显示
go tool cover -func=c.out
Finally, to generate modified source code with coverage annotations
(what go test -cover does):最后,生成带有覆盖率注释的修改过的源代码
(go test -cover做什么):
go tool cover -mode=set -var=CoverageVariableName program.go
coveralls 检测
$COVERALLS_TOKEN 来自https://coveralls.io/ 申请TOKEN
go test -v -covermode=count -coverprofile=coverage.out
# 将测试覆盖状态上传到coveralls网站,生成标签.
${GOPATH}/bin/goveralls -coverprofile=coverage.out -service=travis-ci -repotoken ${COVERALLS_TOKEN}
有疑问加站长微信联系(非本文作者)