第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會有你想問的

測試 http.Pusher 和 golang 中的推送功能

測試 http.Pusher 和 golang 中的推送功能

Go
搖曳的薔薇 2023-06-26 16:53:51
我正在嘗試為 http.Pusher 編寫單元測試。我嘗試使用 httptest.NewRecorder() 作為 http.ResponseWriter 但類型轉(zhuǎn)換失敗。我還能如何編寫測試?    //My function     func push(w http.ResponseWriter, resource string) error {        pusher, ok := w.(http.Pusher)        if ok {            return pusher.Push(resource, nil)        }        return fmt.Errorf("Pusher not supported")    }    //My test     func TestPush(t *testing.T) {        resource := "static/css/main.css"        response := httptest.NewRecorder()        got := push(response, resource)        if got != nil {            t.Errorf("Error : %v", got)        }    }輸出是“不支持 Pusher”,我認(rèn)為 w.(http.Pusher) 失敗了。
查看完整描述

1 回答

?
瀟瀟雨雨

TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊

您可以創(chuàng)建一個(gè)http.ResponseWriter也實(shí)現(xiàn) 的模擬http.Pusher,并在測試期間通過它。

這是適合您的可測試函數(shù)的簡單實(shí)現(xiàn):

type pusher struct {

? ? http.ResponseWriter

? ? err? ? error // err to return from Push()

? ? target string

? ? opts? ?*http.PushOptions

}


func (p *pusher) Push(target string, opts *http.PushOptions) error {

? ? // record passed arguments for later inspection

? ? p.target = target

? ? p.opts = opts

? ? return p.err

}

測試函數(shù)示例:


func TestPush(t *testing.T) {

? ? resource := "static/css/main.css"

? ? p := &pusher{}

? ? err := push(p, resource)


? ? if err != p.err {

? ? ? ? t.Errorf("Expected: %v, got: %v", p.err, err)

? ? }

? ? if resource != p.target {

? ? ? ? t.Errorf("Expected: %v, got: %v", p.target, resource)

? ? }

}

請注意,這個(gè)簡單的pusher嵌入http.ResponseWriter類型將使其本身成為一個(gè)http.ResponseWriter(它將成為pusherImplement http.ResponseWriter)。在測試過程中,我們保留了該字段nil,因?yàn)榭蓽y試push()函數(shù)沒有使用其中的任何內(nèi)容。如果您的真實(shí)函數(shù)會調(diào)用它的方法,例如ResponseWriter.Header(),那當(dāng)然會導(dǎo)致運(yùn)行時(shí)恐慌。在這種情況下,您也必須提供有效的信息http.ResponseWriter,例如:


p := &pusher{ResponseWriter: httptest.NewRecorder()}


查看完整回答
反對 回復(fù) 2023-06-26
  • 1 回答
  • 0 關(guān)注
  • 237 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號