go语言测试方法
测试split
package split
import "strings"
func Split(s, seq string) (result []string) {
i := strings.Index(s, seq)
for i>-1 {
result = append(result, s[:i])
s = s[i+len(seq):]
//s = s[i+1:]
i = strings.Index(s, seq)
}
result = append(result, s)
return result
}
编写的测试函数
package split
import (
"reflect"
"testing"
)
//测试切片为长度为1的字符串时
func TestSplit(t *testing.T) {
got := Split("a:b:c",":")
want := []string{"a", "b", "c"}
if !reflect.DeepEqual(got,want) {
t.Errorf("go= %v, want= %v", got, want)
}
}
//测试长度大于1的字符串切片
func TestMoreSplit(t *testing.T) {
got := Split("abcd", "bc")
want := []string{"a","d"}
if !reflect.DeepEqual(got, want) {
t.Errorf("got= %v, want= %v", got, want)
}
}
//组合测试,多组测试
func TestSplitM(t *testing.T) {
//定义测试用的结构体
type test struct {
input string
seq string
want []string
}
//测试用例使用Map进行存储
tests := []test{
{"a:b:c:d",":",[]string{"a","b","c","d"}},
{"a:b:c",",",[]string{"a:b:c"}},
{"abcd","bc",[]string{"a","d"}},
{"我爱你","爱",[]string{"我","你"}},
}
//使用range循环测试每一个test用例
for _,tc := range tests {
got := Split(tc.input, tc.seq)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("got= %#v, want= %#v", got, tc.want)
}
}
}
//子测试
func TestSplitSample(t *testing.T) {
type test struct{
input string
seq string
want []string
}
tests := map[string]test{
"simple seq" : {"a:b:c",":",[]string{"a","b","c"}},
"wrong seq" : {"a:b:c",",",[]string{"a:b:c"}},
"more seq" : {"abcd","bc",[]string{"a","d"}},
"leading seq" : {"我爱你","爱",[]string{"我","你"}},
}
for name,tc := range tests {
got := Split(tc.input,tc.seq)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("name= %#v, got= %#v, want= %#v", name, got ,tc.want)
}
}
}
func TestSplit2(t *testing.T) {
type test struct {
input string
seq string
want []string
}
tests := map[string]test{
"simple seq" : {"a:b:c",":",[]string{"a","b","c"}},
"wrong seq" : {"a:b:c",",",[]string{"a:b:c"}},
"more seq" : {"abcd","bc",[]string{"a","d"}},
"leading seq" : {"我爱你","爱",[]string{"我","你"}},
}
for name,tc := range tests {
t.Run(name, func(t *testing.T) {
got := Split(tc.input, tc.seq)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("name= %#v, got= %#v, want= %#v", name, got ,tc.want)
}
})
}
}
go 测试使用的命令
//go的测试命令
go test 执行所有的测试Test*方法
go test -v 执行所有测试方法,并查看每一个的测试执行
go test -v -run=*** 执行某一个测试用例
go test -cover 测试覆盖率
go test -cover -coverprofile=c.out 测试覆盖率,并将覆盖率写到文件c.out中
go tool cover -html=c.out 在html中显示覆盖率