一,演示项目相关信息
1,地址:
GitHub - liuhongdi/unittest: go语言做单元测试的常用例子
2,功能:演示了go做单元测试时的分组测试和子测试
3,项目结构:如图:
说明:刘宏缔的go森林是一个专注golang的博客,
网站:https://blog.imgtouch.com
原文: go语言单元测试之一:go语言做单元测试 – 架构森林
说明:作者:刘宏缔 邮箱: 371125307@qq.com
二,代码
1,util/split.go
package util
import "strings"
//字符串切分方法
func Split(s, sep string) (result []string) {
i := strings.Index(s, sep)
for i > -1 {
result = append(result, s[:i])
s = s[i+len(sep):]
i = strings.Index(s, sep)
}
result = append(result, s)
return
}
2,util/split_test.go
package util
import (
"reflect"
"testing"
)
//测试字符串切分
func TestSplit(t *testing.T) {
// test struct
type testcase struct {
input string
sep string
excepted []string
}
// 用例: 用map存储
cases := map[string]testcase{
"冒号分隔": {input: "a:b:c", sep: ":", excepted: []string{"a", "b", "c"}},
"逗号分隔": {input: "a:b:c", sep: ",", excepted: []string{"a:b:c"}},
"字符串分割": {input: "abcd", sep: "bc", excepted: []string{"a", "d"}},
"中文分隔符位于开始": {input: "百度员工百度不到时用google", sep: "百度", excepted: []string{"","员工", "不到时用google"}},
"分隔符last": {input: "abcd", sep: "d", excepted: []string{"abc", ""}},
}
for name, tc := range cases {
// t.Run():执行子测试
t.Run(name, func(t *testing.T) {
got := Split(tc.input, tc.sep)
if !reflect.DeepEqual(got, tc.excepted) {
t.Errorf("excepted:%#v, got:%#v", tc.excepted, got)
}
})
}
}
3,main.go
package main
//定义一个加法方法
func add(a, b int) int {
return a + b
}
4,main_test.go
package main
import (
"testing"
)
//测试add方法
func TestAdd(t *testing.T) {
//列出要测试的参数和返回结果
cases := []struct {
first int
second int
excepted int
}{
{1, 2, 3},
{1, 3, 4},
{2, 2, 4},
}
//遍历,进行测试
for _, c := range cases {
result := add(c.first, c.second)
if result != c.excepted {
t.Fatalf("add function failed, first: %d, second:%d, execpted:%d, result:%d", c.first, c.second, c.excepted, result)
}
/*
else {
fmt.Printf("success:first: %d, second:%d, execpted:%d, result:%d \n", c.first, c.second, c.excepted, result)
}
*/
}
}
5,说明:
测试失败时:
如果使用 t.Error/t.Errorf
:遇到错误不会停,还会继续执行其他的测试用例
如果使用 t.Fatal/t.Fatalf:
遇到错误即停,不会继续执行其他的测试用例
大家根据自己的需要选择
三,测试效果
root@ku:/data/go/unittest# go test -v ./...
=== RUN TestAdd
--- PASS: TestAdd (0.00s)
PASS
ok github.com/liuhongdi/unittest (cached)
=== RUN TestSplit
=== RUN TestSplit/冒号分隔
=== RUN TestSplit/逗号分隔
=== RUN TestSplit/字符串分割
=== RUN TestSplit/中文分隔符位于开始
=== RUN TestSplit/分隔符last
--- PASS: TestSplit (0.00s)
--- PASS: TestSplit/冒号分隔 (0.00s)
--- PASS: TestSplit/逗号分隔 (0.00s)
--- PASS: TestSplit/字符串分割 (0.00s)
--- PASS: TestSplit/中文分隔符位于开始 (0.00s)
--- PASS: TestSplit/分隔符last (0.00s)
PASS
ok github.com/liuhongdi/unittest/util 0.003s
四,查看go的版本:
root@ku:/data/go/unittest# go version
go version go1.15.4 linux/amd64