正确使用httptest模拟响应

tho*_*rca 1 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_response
Run Code Online (Sandbox Code Playgroud)

在测试中,我具有以下几点:

  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)
Run Code Online (Sandbox Code Playgroud)

但是,从日志输出中可以看出,它似乎并没有显示HTTP测试服务器正在运行并且实际上已经进入了test.com。

 Get http:/test.com: dial tcp X.Y.Z.A: i/o timeout
Run Code Online (Sandbox Code Playgroud)

我的问题是如何正确使用httptest软件包来模拟此请求...我阅读了文档和这份很有帮助的SO解答,但仍然遇到问题。

Jim*_*imB 5

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

done := client.CheckURL(ts.URL, json_response)
Run Code Online (Sandbox Code Playgroud)