转载 于 Go语言基础之单元测试
Split包
package split_string
import "strings"
// Split 字符串
func Split(str string, sep string) []string {
var res = make([]string, 0, strings.Count(str, sep)+1)
idx := strings.Index(str, sep)
sep_len := len(sep)
for idx >= 0 {
res = append(res, str[:idx])
str = str[idx+sep_len:]
idx = strings.Index(str, sep)
}
res = append(res, str)
return res
}
Split包 测试组
// split/split_test.go
package split_string
import (
"reflect"
"testing"
)
func TestSplit(t *testing.T) {
type test struct { // 定义test结构体
input string
sep string
want []string
}
tests := map[string]test{ // 测试用例使用map存储
"simple": {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
"wrong sep": {input: "a:b:c", sep: ",", want: []string{"a:b:c"}},
"more sep": {input: "abcd", sep: "bc", want: []string{"a", "d"}},
"leading sep": {input: "上海自来水来自海上", sep: "海", want: []string{"上", "自来水来自", "上"}},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) { // 使用t.Run()执行子测试
got := Split(tc.input, tc.sep)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("excepted:%#v, got:%#v", tc.want, got)
}
})
}
}
上课笔记
1.go test -v
: 直接显示test后的结果,不需要编译
2.go test -cover -coverprofile=cover.out
覆盖率输出成文本形式
3.go tool cover -html=cover.out
以HTML的形式查看其覆盖率的情况
4.func TestSplit(t *testing.T)
:必须以Test
开头,同时参数是固定为t *testing.T