13.9 用(測試數據)表驅動測試
編寫測試代碼時,一個較好的辦法是把測試的輸入數據和期望的結果寫在一起組成一個數據表:表中的每條記錄都是一個含有輸入和期望值的完整測試用例,有時還可以結合像測試名字這樣的額外信息來讓測試輸出更多的信息。
實際測試時簡單迭代表中的每條記錄,並執行必要的測試。這在練習 13.4 中有具體的應用。
可以抽象爲下面的代碼段:
var tests = []struct{ // Test table
in string
out string
}{
{“in1”, “exp1”},
{“in2”, “exp2”},
{“in3”, “exp3”},
...
}
func TestFunction(t *testing.T) {
for i, tt := range tests {
s := FuncToBeTested(tt.in)
if s != tt.out {
t.Errorf(“%d. %q => %q, wanted: %q”, i, tt.in, s, tt.out)
}
}
}
如果大部分函數都可以寫成這種形式,那麼寫一個幫助函數 verify 對實際測試會很有幫助:
func verify(t *testing.T, testnum int, testcase, input, output, expected string) {
if input != output {
t.Errorf(“%d. %s with input = %s: output %s != %s”, testnum, testcase, input, output, expected)
}
}
TestFunction 則變爲:
func TestFunction(t *testing.T) {
for i, tt := range tests {
s := FuncToBeTested(tt.in)
verify(t, i, “FuncToBeTested: “, tt.in, s, tt.out)
}
}
鏈接
- 目錄
- 上一節:測試的具體例子
- 下一節:性能調試:分析並優化 Go 程序