1 回答

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超11個(gè)贊
為了不讓測試過于復(fù)雜,我建議您采用這種方法。首先,首先定義您的錯(cuò)誤:
type timeoutError struct {
err string
timeout bool
}
func (e *timeoutError) Error() string {
return e.err
}
func (e *timeoutError) Timeout() bool {
return e.timeout
}
這樣,timeoutError同時(shí)實(shí)現(xiàn)了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,
}
}
這只是返回上面定義的錯(cuò)誤并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())
}
如果您調(diào)試此測試并在變量上使用調(diào)試器暫停err,您將看到想要的結(jié)果。
由于這種方法,您可以在不增加任何額外復(fù)雜性的情況下實(shí)現(xiàn)所需的功能。讓我知道是否適合你!
- 1 回答
- 0 關(guān)注
- 129 瀏覽
添加回答
舉報(bào)