ZVVQ代理分享网

使用 Go 框架进行代码覆盖率分析的技巧(代码覆

作者:zvvq博客网
导读使用 go 框架进行代码覆盖率分析的技巧包括:安装 gocov、coverage 或 gotestsum 等覆盖率框架。使用 go test -cover 命令运行测试以生成覆盖率报告。使用 coverage 创建不同格式的报告。使用

应用 go 架构开展代码覆盖率剖析技巧包含:组装 gocov、coverage 或 gotestsum 等普及率架构。应用 go test-cover指令运行测试以形成普及率汇报。应用coverage 建立不一样格式汇报。应用 gotestsum 合拼好几个测试代码的普及率结论。根据合拼好几个测试覆盖率结论去解决实战案例 。

应用 Go 架构开展代码覆盖率剖析技巧

介绍代码覆盖率是一个重要的指标值,用以考量手机中已检测代码比例。对 Go 应用软件开展代码覆盖率剖析能够帮助鉴别未遮盖代码途径并提升测试覆盖率。下面我们就讨论应用最流行的 Go 架构,比如 Gocov、Coverage 和 Gotestsum,开展代码覆盖率剖析技巧。

组装普及率架构最先,组装所需要的 Go 普及率架构:

gogetgithub.com/axw/gocov

gogetgithub.com/wadey/gocovmerge

gogetgithub.com/gotestyourself/gotestsum

GocovGocov 是一款轻量且简单 Go 普及率专用工具。需要使用 Gocov,请于要搞清楚代码中导进其包:

import"github.com/axw/gocov"

随后,应用 go test-cover指令运行测试,该指令将于 coverage.out 文档中形成普及率汇报:

gotest-cover

可以使用 gocovview coverage.out 指令查看报告。

CoverageCoverage 是一个功能丰富的普及率数据分析工具,它提供了建立不一样文件格式汇报(包含 HTML 和 JSON)这个选项。需要使用 Coverage,请建立下列环境变量:

//.coverprofile

mode:set

//thedirectorytooutputprofilesunder

output:coverage

//requiredfor Go 1.13+

root:github.com/your-organization/your-project

随后,应用 -coverprofile=.coverprofile 标示运行测试:

gotest-coverprofile=.coverprofile

Coverage 将生成一个名叫 coverage.out 的普及率文档。应用coverage view coverage.out 指令查看报告。

GotestsumGotestsum是一款多稳定性测试器,它允许您合拼好几个测试代码的普及率结论。需要使用 Gotestsum,请选择 -coverreport=coverage.out 标示运行测试:

gotestsum--coverreport=coverage.out

Gotestsum将生成一个合并的 coverage.out 文档,其中包括所有应用的普及率结论。

实战案例

下面是一个应用 Gocov和 Gocovmerge合拼好几个测试覆盖率过程的实战案例 :

packagemain

import(

"github.com/axw/gocov"

"github.com/wadey/gocovmerge"

"os"

)

funcmain(){

//创建新普及率文档

covfile := "coverage.out"

f, err := os.Create(covfile)

if err != nil {

panic(err)

}

defer f.Close()

// 循环遍历全部测试目标

files := []string{"test1.go", "test2.go"}

for _, file := range files {

// 为每一个总体目标形成普及率文档

gocov.Run(file)

// 增加普及率数据到主文件

data, err := os.ReadFile("coverage.out")

if err != nil {

panic(err)

}

if _, err := f.Write(data); err != nil {

panic(err)

}

}

// 合拼同样包中所有普及率文档

iferr:= gocovmerge.MergeProfiles(covfile,covfile);err!=nil{

panic(err)

}

}

之上就是采用 Go 架构开展代码覆盖率剖析技巧的详细内容,大量欢迎关注其他类似文章!