1 回答

TA貢獻1744條經驗 獲得超4個贊
如果我理解正確,您希望在某些條件下檢查正確的錯誤返回。
這是:
func coolFunction(input int) (int, error) {
var err error
var number int
if input == 1 {
err = errors.New("This is an error")
number = 400
} else {
err = nil
number = 200
}
return number, err
}
然后在測試文件中,您需要對預期錯誤的事實(理所當然)有一個理解或協議。就像下面的標志一樣,這對于您的情況來說是正確的。expectError bool
您還可以為特定錯誤類型設置字段,并檢查返回的類型是否正是該字段。
func TestCoolFunction(t *testing.T) {
var testTable = []struct {
desc string
in int
expectError bool
out int
}{
{"Should_fail", 1, true, 0},
{"Should_pass", 100, false, 200},
}
for _, tt := range testTable {
t.Run(tt.desc, func(t *testing.T) {
out, err := coolFunction(tt.in)
if tt.expectError {
if err == nil {
t.Error("Failed")
}
} else {
if out != tt.out {
t.Errorf("got %d, want %d", out, tt.out)
}
}
})
}
}
使用@mkopriva建議添加特定的錯誤檢查DeepEqual
func TestCoolFunction(t *testing.T) {
var testTable = []struct {
desc string
in int
expectError error
out int
}{
{"Should_fail", 1, errors.New("This is an error"), 0},
{"Should_pass", 100, nil, 200},
}
for _, tt := range testTable {
t.Run(tt.desc, func(t *testing.T) {
out, err := coolFunction(tt.in)
if tt.expectError != nil {
if !reflect.DeepEqual(err, tt.expectError) {
t.Error("Failed")
}
} else {
if out != tt.out {
t.Errorf("got %d, want %d", out, tt.out)
}
}
})
}
}
另外,為了演示,您應該使用一些不同的方法來檢查更快的錯誤。這取決于應用程序中錯誤的設計方式。您可以使用哨兵錯誤或類型/接口檢查。或者自定義錯誤類型中基于 const 的枚舉字段。DeepEqual
- 1 回答
- 0 關注
- 99 瀏覽
添加回答
舉報