Golang測(cè)試func?TestXX(t?*testing.T)的使用詳解
一般Golang中的測(cè)試代碼都以xxx_test.go的樣式,在命名測(cè)試函數(shù)的時(shí)候以Testxx開頭。
以下是我寫的一個(gè)單元:
package tests
import "strings"
func Split(s, sep string) (res []string) {
i := strings.Index(s, sep)
for i > -1 {
res = append(res, s[:i])
s = s[i+len(sep):]
i = strings.Index(s, sep)
}
res = append(res, s)
return
}第一種測(cè)試方法:
func TestSplit(t *testing.T) {
inputs := Split("a:b:c", ":")
want := []string{"a", "b", "c"}
if !reflect.DeepEqual(inputs, want) {
t.Errorf("inputs:%v, want:%v", inputs, want)
}
}這種直接定義好輸入、期望值,進(jìn)行對(duì)比,這種不適合大量數(shù)據(jù)比較。
第二種測(cè)試方法:
func TestSplit(t *testing.T) {
testCases := []struct {
input string
sep string
want []string
}{
{input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
{input: "a:b:c", sep: ",", want: []string{"a:b:c"}},
{input: "abcd", sep: "bc", want: []string{"a", "d"}},
}
for _, tc := range testCases {
got := Split(tc.input, tc.sep)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("期望值:%v,實(shí)際值:%v\n", tc.want, got)
}
}
}使用結(jié)構(gòu)體測(cè)試,然后使用for range遍歷,是比較方便的方式,但是如果我的測(cè)試數(shù)據(jù)很多,但是我其中一個(gè)測(cè)試出現(xiàn)錯(cuò)誤了,我現(xiàn)在需要找到那一個(gè),那么這個(gè)方式就有點(diǎn)不適用了。
第三種測(cè)試方法(推薦使用):
func TestSplit(t *testing.T) {
testCases := map[string]struct {
input string
sep string
want []string
}{
"one": {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
"two": {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
"three": {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
"four": {input: "a:b:c", sep: ":", want: []string{"a", "b", "c"}},
"five": {input: "a:b:c", sep: ":", want: []string{"b", "b", "c"}},
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
got := Split(tc.input, tc.sep)
if !reflect.DeepEqual(got, tc.want) {
t.Errorf("期望值:%v,實(shí)際值:%v", tc.want, got)
}
})
}
}
這里我們使用子測(cè)試的方法,主要可以看到第五個(gè)測(cè)試案例直接報(bào)錯(cuò),信息并顯示出來。
同樣,也有一些其他的測(cè)試方法,后續(xù)如果了解更多的話,在這里補(bǔ)上。
到此這篇關(guān)于Golang測(cè)試func TestXX(t *testing.T)的使用的文章就介紹到這了,更多相關(guān)Golang測(cè)試func TestXX使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Golang自定義結(jié)構(gòu)體轉(zhuǎn)map的操作
這篇文章主要介紹了Golang自定義結(jié)構(gòu)體轉(zhuǎn)map的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12
golang 微服務(wù)之gRPC與Protobuf的使用
這篇文章主要介紹了golang 微服務(wù)之gRPC與Protobuf的使用,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-02-02
go開源Hugo站點(diǎn)構(gòu)建三步曲之集結(jié)渲染
這篇文章主要為大家介紹了go開源Hugo站點(diǎn)構(gòu)建三步曲之集結(jié)渲染詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02

