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

如何在 Golang 单元测试中使用表驱动的测试方法?
表驱动的测试是一种测试方法,它使用一个表来定义多个输入和预期输出。这可以简化和加快编写测试用例的过程,因为我们只需要定义表本身,而不是为每个测试用例编写单独的函数。
语法
表驱动的测试语法如下:
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 检查结果是否与预期输出匹配。
实战案例
以下是一个将字符串转换为大写的函数的表驱动的测试:
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 <a style='color:#f60; text-decoration:underline;' href="https://www.php.cn/zt/15841.html" target="_blank">git</a>hub.com/user/pkg 0.005s
登录后复制
以上就是如何在 Golang 单元测试中使用表驱动的测试方法?的详细内容,更多请关注叮当号网其它相关文章!
文章来自互联网,只做分享使用。发布者:走不完的路,转转请注明出处:https://www.dingdanghao.com/article/497102.html
