go单元测试

Jimmy Lee

学习思考|May 6, 2022|Last edited: 2022-7-27|
icon
Update time
Jul 27, 2022 10:57 PM
Internal status
READY TO PUBLISH
password
go语言默认带测试工具,如果想递归测试目录下的所有测试代码,则可以执行以下代码
 
go test -mod=vendor -covermode=count -coverprofile=coverprofile.cov -run="^Test" -coverpkg=$(go list -mod=vendor ./... | grep -v "/test" | tr '\n' ',') ./... // 或 非 vendor 模式: go test -covermode=count -coverprofile=coverprofile.cov -run="^Test" -coverpkg=$(go list ./... | grep -v "/test" | tr '\n' ',') ./...
生成结果:coverprofile.cov
指令简单说明: mod=vendor: 加载依赖的方式:从本地vendor 目录加载。适用于服务器不能从外网下载依赖的情况 covermode: count: 统计代码访问次数;set: 统计代码是否被访问; atomic: 一般在并发工程中使用(?) run: 正则方式指定需要运行的测试方法 coverpkg: 指定业务代码路径,多个用逗号隔开,详细说明在后面 ./…:遍历当前目录下测试文件,包括子目录
 
关于为什么要使用coverpkg:
主要是因为我们的项目结构中,测试代码和业务代码是分开的,而不是放到同一个目录中。因此如果只指定测试方法,就无法识别到业务代码,来计算覆盖率了。 因此我们既需要指定测试代码路径(当然这里声明为 ./… 就可以了,只有_test 结尾的方法会自动作为测试方法),也需要指定业务代码路径(通过grep -v 和 tr 指令,最终将业务代码输出成 git/controller,git/database 的格式)
 
2、打开覆盖率报告 通过html 文件打开(推荐,能看到方法细节): go tool cover -html=coverprofile.cov
在命令行直接查看: go tool cover -func=coverprofile.cov

开始订阅我的关于终生学习, 生产力以及知识管理的文章. 订阅后, 您将收到我的精选文章.

©2014-2024 Jimmy Lee. All rights reserved. 公众号: 技术管理方法论
Powered By My Lovely Children