1 回答

TA貢獻1775條經驗 獲得超11個贊
為了不讓測試過于復雜,我建議您采用這種方法。首先,首先定義您的錯誤:
type timeoutError struct {
err string
timeout bool
}
func (e *timeoutError) Error() string {
return e.err
}
func (e *timeoutError) Timeout() bool {
return e.timeout
}
這樣,timeoutError同時實現了Error()和Timeout接口。
然后你必須為 HTTP 客戶端定義模擬:
type mockClient struct{}
func (m *mockClient) Do(req *http.Request) (*http.Response, error) {
return nil, &timeoutError{
err: "context deadline exceeded (Client.Timeout exceeded while awaiting headers)",
timeout: true,
}
}
這只是返回上面定義的錯誤并nil作為 http.Response。最后,讓我們看看如何編寫示例單元測試:
func TestSlowServer(t *testing.T) {
r := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
client := &mockClient{}
_, err := client.Do(r)
fmt.Println(err.Error())
}
如果您調試此測試并在變量上使用調試器暫停err,您將看到想要的結果。
由于這種方法,您可以在不增加任何額外復雜性的情況下實現所需的功能。讓我知道是否適合你!
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報