简体   繁体   中英

Correctly using httptest to mock responses

I have something that looks like so:

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

And in my test, I have the following:

  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)

However, it does not appear as if the HTTP test server is working and that it actually goes out to test.com, as evidenced by the log output:

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

My question is how to properly use the httptest package to mock out this request... I read through the docs and this helpful SO Answer but I'm still stuck.

Your client only calls the URL you provided as the first argument to the CheckURL method. Give your client the URL of your test server:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM