func TestAdd(t *testing.T) {
a := 10
b := 20
wanted := 30
actual := add(a, b)
if wanted != actual {
t.Errorf("[add函数的入参:%d %d] [期望值:%d] [实际结果:%d]", a, b, wanted, actual)
}
}
执行当前单元测试的命令: go test -v .\user_test.go
PS C:\Program Files\JetBrains\GoRepository\gf-demo-user\internal\service> go test -v .\user_test.go
=== RUN TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok command-line-arguments 0.075s
执行当前目录下所有的测试用例(跳过某个测试函数),并导出到制定的输出文件:go test -v ./... --short=true -coverprofile cover.out
PS C:\Program Files\JetBrains\GoRepository\gf-demo-user\internal\service> go test -v ./... --short=true -coverprofile cover.out
=== RUN TestAdd
--- PASS: TestAdd (0.00s)
coverage: 0.0% of statements
ok github.com/gogf/gf-demo-user/v2/internal/service 0.121s coverage: 0.0% of statements
真实案例 被测试的函数
func Split(s, sub string) (result []string) {
if len(strings.TrimSpace(s)) == 0 {
return
}
i := strings.Index(s, sub)
for i > -1 {
if i == 0 {
s = s[len(sub):]
} else {
result = append(result, s[:i])
s = s[i+len(sub):]
}
i = strings.Index(s, sub)
}
result = append(result, s)
return
}
简单的测试
get := Split("a:b:c", ":")
wanted := []string{"a", "b", "c"}
if !reflect.DeepEqual(wanted, get) {
t.Errorf("expected:%v,get:%v", wanted, get)
}
多维度测试案例
func TestMultiSplit(t *testing.T) {
type test struct {
name string
input string
sub string
wanted []string
}
tests := []test{
{name: "正常的测试用例", input: "a:b:c", sub: ":", wanted: []string{"a", "b", "c"}},
{name: "字符串头位置匹配测试", input: ":a:b:c", sub: ":", wanted: []string{"a", "b", "c"}},
{name: "无匹配项的测试", input: "abc", sub: ":", wanted: []string{"abc"}},
{name: "英文串的测试", input: "abcd", sub: "bc", wanted: []string{"a", "d"}},
{name: "中文串的测试", input: "云原生", sub: "云", wanted: []string{"原生"}},
}
for _, d := range tests {
get := Split(d.input, d.sub)
if !reflect.DeepEqual(d.wanted, get) {
t.Errorf("[testName:%v][expected:%v] [get:%v]", d.name, d.wanted, get)
}
}
}