正确使用 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

我的问题是如何正确使用 httptest 包来模拟这个请求......我通读了文档和这个有用的SO Answer但我仍然卡住了。


泛舟湖上清波郎朗
浏览 230回答 1
1回答

慕莱坞森

您的客户端仅调用您提供的 URL 作为该CheckURL方法的第一个参数。为您的客户提供测试服务器的 URL:done := client.CheckURL(ts.URL, json_response)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go