Unit testing 正确使用httptest模拟响应

Unit testing 正确使用httptest模拟响应,unit-testing,go,Unit Testing,Go,我有些东西看起来是这样的: 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_respon

我有些东西看起来是这样的:

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

我的问题是如何正确使用httptest包模拟这个请求。。。我通读了一遍,这很有帮助,但我还是被卡住了。

您的客户端只调用您作为CheckURL方法的第一个参数提供的URL。为客户端提供测试服务器的URL:

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

您的客户端只调用您作为CheckURL方法的第一个参数提供的URL。为客户端提供测试服务器的URL:

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

我错过了这个关键点,重新阅读文档/示例,这非常有意义。我错过了这个关键点,重新阅读文档/示例,这非常有意义。