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()}
- 1 回答
- 0 關(guān)注
- 237 瀏覽
添加回答
舉報(bào)