如何覆盖 golang 单元测试中的代码?方法:使用内置的 cover 工具(go test -cover)。利用第三方库,如 testify 的 assert 函数。实战示例:使用 cover 工具和 testify 断言函数,可测量 factorial 函数的代码覆盖率,生成 html 报告展示详细信息。
如何覆盖 Golang 单元测试中的代码?
介绍
代码覆盖率是一个衡量测试套件涵盖目标代码份额的指标。在单元测试中,高代码覆盖率表明已测试了大部分业务逻辑,提高了测试的可靠性。
方法
1. 使用代码覆盖率工具
Go 语言提供了 cover 工具来测量代码覆盖率。要使用它,除了正常的 go test 命令外,还需要添加 -cover 标志:
go test -cover
2. 利用第三方库
还有许多第三方库可以提供更详细的代码覆盖率报告。例如,可以使用 testify 中的 assert 函数:
import (
"testing"
"<a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/15841.html" target="_blank">git</a>hub.com/stretchr/testify/assert"
)
func TestSomething(t *testing.T) {
assert.Equal(t, 1, something()) // 覆盖了 something() 函数的 return 语句
}
实战案例
下面是一个简单的 Go 语言函数和相关的单元测试:
// main.go
package main
func Factorial(n int) int {
if n == 0 {
return 1
}
return n * Factorial(n-1)
}
func main() {
println(Factorial(5)) // 输出:120
}
// factorial_test.go
package main
import "testing"
func TestFactorial(t *testing.T) {
// 记录 Factorial 函数的覆盖率
t.Run("Cover", func(t *testing.T) {
cases := []int{0, 1, 5, 10}
for _, n := range cases {
Factorial(n)
}
})
}
运行测试:
go test -cover -coverprofile=cover.out
然后,使用 go tool cover -html=cover.out 生成 HTML 报告,该报告显示了覆盖率详细信息。