首頁  >  文章  >  後端開發  >  為具有超時的單元測試創建一個deadlineExceededError:true

為具有超時的單元測試創建一個deadlineExceededError:true

WBOY
WBOY轉載
2024-02-09 13:00:18667瀏覽

為具有超時的單元測試創建一個deadlineExceededError:true

php小編小新在這裡為大家介紹一個有關單元測試的技巧:為帶有超時的單元測試創建一個deadlineExceededError:true。在進行單元測試時,有時可能會遇到測試執行逾時的情況,這時我們可以透過設定deadlineExceededError為true來解決這個問題。這個技巧可以幫助我們更好地控制和管理測驗的執行時間,確保測驗的準確性和可靠性。接下來,我們將詳細介紹如何運用這個技巧來提升單元測試的效率和可靠性。

問題內容

我正在嘗試在我的專案中建立一個單元測試,在其中模擬 http 客戶端並設定客戶端必須返回的回應。 我需要這樣的行為,因為我的程式碼需要做出相應的行為,以防 http 客戶端因超時而失敗:因此我需要模擬 http 客戶端以返回一個 deadlineexceedederror 並從中進行單元測試。

到目前為止,我嘗試的是以 client.do 返回的方式模擬客戶端 do 函數:

getdofunc = func(*http.request) (*http.response, error) {
    return nil, &url.error{
        op:  "post",
        err: context.deadlineexceeded,
    }
}

它可以工作,但不完全,這意味著當我以這種模擬行為執行程式碼時,返回的錯誤類型是:

error(*net/url.error) *{op: "post", url: "", err: error(context.deadlineexceedederror) {}}

這又是正確的,但不完全。為什麼?因為如果我運行程式碼並且發生真正的超時,我會得到更完整的東西:

error(*net/url.Error) *{Op: "Post", URL: "http://localhost:4500/scan/", Err: error(*net/http.httpError) *{err: "context deadline exceeded (Client.Timeout exceeded while awaiting headers)", timeout: true}}

最讓我感興趣的是timeout: true。如果我設法告訴我的模擬返回它,我可以斷言這一點,我發現這比僅斷言返回的錯誤是 deadlineexceedederror 類型更完整。

解決方法

為了避免測試過於複雜,我建議您採用這種方法。首先,先定義您的錯誤:

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 變數上使用偵錯器暫停,您將看到想要的結果。
透過這種方法,您可以實現所需的功能,而無需帶來任何額外的複雜性。讓我知道是否適合您!

以上是為具有超時的單元測試創建一個deadlineExceededError:true的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除