亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

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

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

Go
搖曳的薔薇 2023-06-26 16:53:51
我正在嘗試為 http.Pusher 編寫單元測試。我嘗試使用 httptest.NewRecorder() 作為 http.ResponseWriter 但類型轉換失敗。我還能如何編寫測試?    //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”,我認為 w.(http.Pusher) 失敗了。
查看完整描述

1 回答

?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

您可以創建一個http.ResponseWriter也實現 的模擬http.Pusher,并在測試期間通過它。

這是適合您的可測試函數的簡單實現:

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

}

測試函數示例:


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)

? ? }

}

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


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


查看完整回答
反對 回復 2023-06-26
  • 1 回答
  • 0 關注
  • 248 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號