2016-06-13 37 views
0

我有東西,看起來像這樣:正確使用httptest嘲笑迴應

func (client *MyCustomClient) CheckURL(url string, json_response *MyCustomResponseStruct) bool { 
    r, err = http.Get(url) 
    if err != nil { 
     return false 
    } 
    defer r.Body.Close() 
    .... do stuff with json_response 

而在我的測試中,我有以下幾點:

func TestCheckURL(t *test.T) { 
     ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 
      w.Header().Set("Content-Type", "text/html; charset=UTF-8") 
      fmt.Fprintln(w, `{"status": "success"}`) 
     })) 
     defer ts.Close() 

     json_response := new(MyCustomResponseStruct) 
     client := NewMyCustomClient() // returns instance of MyCustomClient 
     done := client.CheckURL("test.com", json_response) 

但是,它不會出現好像HTTP測試服務器正在工作,它實際上出去test.com,由日誌輸出證明:

Get http:/test.com: dial tcp X.Y.Z.A: i/o timeout 

我的問題是如何t o正確使用httptest包嘲笑這個請求...我通過the docs和這有幫助SO Answer通讀,但我仍然卡住。

回答

3

您的客戶端只會調用您提供的URL作爲CheckURL方法的第一個參數。爲您的客戶端提供您的測試服務器的網址:

done := client.CheckURL(ts.URL, json_response) 
+0

我錯過了這個關鍵位,重新閱讀了文檔/示例,這是非常有意義的。 – thomascirca