2

Go 代码测试覆盖度

 2 years ago
source link: https://junhaideng.github.io/2022/04/10/golang/fundamental/test/cover/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
5 个月前发表3 分钟读完 (大约419个字)2 次访问

Go 代码测试覆盖度

在 Go 语言中,本身提供了一些命令来展示代码的覆盖度,我们可以通过执行这些命令来查看哪些语句被测试覆盖到了,哪些没有,进而可以编写更多的 case 来提高代码的覆盖度。

执行下面的命令,可以得出项目里面所有 package 的覆盖度

go test ./... -cover

输出结果如下:

?       github.com/junhaideng/sphincs/api       [no test files]
? github.com/junhaideng/sphincs/cmd [no test files]
ok github.com/junhaideng/sphincs/common 0.462s coverage: 51.9% of statements
? github.com/junhaideng/sphincs/hash [no test files]
ok github.com/junhaideng/sphincs/merkle 0.467s coverage: 68.2% of statements
? github.com/junhaideng/sphincs/rand [no test files]
ok github.com/junhaideng/sphincs/signature 1.367s coverage: 92.3% of statements

如果说我们想要单独看一个 package 中测试 case 所达到的覆盖度,可以指定包的名称

设置 -count=1 可以避免代码没修改导致的缓存,通俗来讲就是重新跑一遍

go test  github.com/junhaideng/sphincs/signature -cover -count=1

如果想要查看哪些具体行被覆盖了,可以设置 -coverprofile 参数,

go test  github.com/junhaideng/sphincs/signature -cover -count=1  -coverprofile="cover.out"

然后将输出的文件转换成 html 文件

go tool cover -html="cover.out" -o cover.html

使用浏览器打开 html 文件,可以显示到那些代码行被覆盖了,哪些没有,这里的红色的表示测试没有覆盖到,绿色表示覆盖到了,灰色表示不用计算的行

cover-html.png

提高代码的测试覆盖度有利于发现问题所在,但是一味的追求测试覆盖率会花费更多的时间,得不偿失。


生活杂笔,学习杂记,偶尔随便写写东西。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK