表驱动的测试在 go 单元测试中通过表定义输入和预期输出简化了测试用例编写。语法包括:1. 定义一个包含测试用例结构的切片;2. 循环遍历切片并比较结果与预期输出。 实战案例中,对字符串转换大写的函数进行了表驱动的测试,并使用 go test 运行测试,打印通过结果。

表驱动的测试是一种测试方法,它使用一个表来定义多个输入和预期输出。这可以简化和加快编写测试用例的过程,因为我们只需要定义表本身,而不是为每个测试用例编写单独的函数。
表驱动的测试语法如下:
import "testing"
func TestTableDriven(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"a", "A"},
{"b", "B"},
{"c", "C"},
}
for _, test := range tests {
result := UpperCase(test.input)
if result != test.expected {
t.Errorf("Expected %q, got %q", test.expected, result)
}
}
}tests 是一个结构体切片,它定义了要测试的输入和预期输出。range tests 循环遍历 tests 切片中的每个测试用例。result 是要测试的函数的输出。if result != test.expected 检查结果是否与预期输出匹配。以下是一个将字符串转换为大写的函数的表驱动的测试:
立即学习“go语言免费学习笔记(深入)”;
import (
"testing"
"strings"
)
func TestUpperCase(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"a", "A"},
{"b", "B"},
{"c", "C"},
}
for _, test := range tests {
result := strings.ToUpper(test.input)
if result != test.expected {
t.Errorf("Expected %q, got %q", test.expected, result)
}
}
}要运行测试,请使用 go test:
go test -v
这将打印以下输出:
=== RUN TestUpperCase --- PASS: TestUpperCase (0.00s) PASS ok github.com/user/pkg 0.005s
以上就是如何在 Golang 单元测试中使用表驱动的测试方法?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号