[Translation]Golang中的表驅動測試

翻譯自<Table driven tests in Go> by Alex Pliutau 2018/08/07git

原文連接github

practice-go中咱們常常使用表驅動測試來測試全部可能的函數使用場景。例如FindAnagrams()函數對於給定輸入返回字典中找到的字謎列表。數組

爲了可以正確測試FindAnagrams()函數,咱們須要測試各類狀況,例如空輸入,有效輸入,無效輸入等。咱們能夠修改不一樣斷言來實現測試,可是使用表測試要容易得多。函數

假設有如下函數:單元測試

FindAnagrams(string word) []string

這是「表」看起來的樣子:測試

var tests = []struct {  
 name string  
 word string  
 want []string  
}{  
 {"empty input string", "", []string{}},  
 {"two anagrams", "Protectionism", []string{"Cite no imports", "Nice to imports"}},  
 {"input with space", "Real fun", []string{"funeral"}},  
}

一般,表是匿名結構體數組切片,能夠定義結構體或使用已經存在的結構進行結構體數組聲明。name屬性用來描述特定的測試用例。spa

有了表以後,咱們能夠簡單地進行迭代和斷言:翻譯

func TestFindAnagrams(t *testing.T) {  
    for _, tt := range tests {  
        t.Run(tt.name, func(t *testing.T) {  
            got := FindAnagrams(tt.word)  
            if got != tt.want {  
                t.Errorf("FindAnagrams(%s) got %v, want %v", tt.word, got, tt.want)  
            }  
        })  
    }  
}

可使用其餘函數代替t.Errorf()函數,t.Errorf()僅僅記錄錯誤並繼續測試。code

在Go中很流行的Testify斷言包使單元測試明確,好比:get

assert.Equal(t, got, tt.want, "they should be equal")

t.Run()將啓動一個子測試,而且若是您以詳細模式運行測試( go test -v),您將看到每一個子測試結果:

=== RUN   TestFindAnagrams  
=== RUN   TestFindAnagrams/empty_input_string  
=== RUN   TestFindAnagrams/two_anagrams  
=== RUN   TestFindAnagrams/input_with_space`

因爲Go 1.7測試包容許使用(*testing.T).Parallel()來並行子測試。請確保並行化測試是有意義的!

t.Run(tt.name, func(subtest *testing.T) {  
 subtest.Parallel()  
 got := FindAnagrams(tt.word)  
 // assertion  
})

就是這樣,享受在Go中進行表驅動測試吧!

相關文章
相關標籤/搜索