在 go 单元测试中使用 go test -cover 命令测量覆盖率,并指定 -cover 或 -coverprofile 选项以生成结果;-covermode 选项可设置覆盖模式(set、count 或 atomic)。实战案例演示了如何编写测试,并使用覆盖率配置文件和 go tool cover 命令生成覆盖率报告。

如何使用覆盖工具在 Golang 单元测试中测试覆盖率
覆盖工具在单元测试中非常重要,因为它可以帮助您识别代码中未被测试的部分。这对于确保代码的质量和可靠性至关重要。在 Golang 中,可以使用 go test -cover 命令来测量单元测试中的覆盖率。
安装覆盖工具
立即学习“go语言免费学习笔记(深入)”;
要在 Golang 中使用覆盖工具,您需要安装它。您可以使用以下命令进行安装:
go install golang.org/x/tools/cmd/cover
测量覆盖率
要测量单元测试的覆盖率,请使用 go test 命令并指定 -cover 标志。该标志随后可以接受以下值:
-covermode=mode:设置覆盖模式。可接受的值包括:
实战案例
以下是一个演示如何测量 Golang 单元测试中覆盖率的简要示例:
main.go
package main
import (
"fmt"
"strconv"
)
// Add two numbers
func Add(a, b int) int {
return a + b
}
// Convert a string to a number
func StrToInt(s string) int {
n, err := strconv.Atoi(s)
if err != nil {
fmt.Println(err.Error())
return 0
}
return n
}main_test.go
package main
import (
"testing"
)
func TestAdd(t *testing.T) {
tests := []struct {
a int
b int
want int
}{
{1, 2, 3},
{0, 0, 0},
{-1, -1, -2},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("TestAdd%d_%d", tt.a, tt.b), func(t *testing.T) {
if got := Add(tt.a, tt.b); got != tt.want {
t.Errorf("Add(%d, %d) = %d, want %d", tt.a, tt.b, got, tt.want)
}
})
}
}
func TestStrToInt(t *testing.T) {
tests := []struct {
s string
want int
}{
{"1", 1},
{"0", 0},
{"-1", -1},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("TestStrToInt%s", tt.s), func(t *testing.T) {
if got := StrToInt(tt.s); got != tt.want {
t.Errorf("StrToInt(%s) = %d, want %d", tt.s, got, tt.want)
}
})
}
}
func TestCoverage(t *testing.T) {
t.Run("Add", func(t *testing.T) {
coverProfile := "add_coverage.out"
args := []string{"-test.coverprofile=" + coverProfile, "-test.covermode=set"}
cmd := exec.Command("go", "test", args...)
if err := cmd.Run(); err != nil {
t.Fatalf("Could not run coverage test: %v", err)
}
})
t.Run("StrToInt", func(t *testing.T) {
coverProfile := "str_int_coverage.out"
args := []string{"-test.coverprofile=" + coverProfile, "-test.covermode=set"}
cmd := exec.Command("go", "test", args...)
if err := cmd.Run(); err != nil {
t.Fatalf("Could not run coverage test: %v", err)
}
})
}在命令行中执行以下命令以生成覆盖率报告:
go test -test.coverprofile=coverage.out
这将在 coverage.out 文件中创建一个覆盖率报告。您可以使用 go tool cover 命令查看报告:
go tool cover -html=coverage.out
这将在浏览器中打开一个 HTML 报告,显示未覆盖的代码行和文件。
以上就是如何在 Golang 单元测试中使用覆盖工具?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号