douya1974 2016-06-13 17:19
浏览 61
已采纳

正确使用httptest模拟响应

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.

  • 写回答

1条回答 默认 最新

  • dpgvdfg321041670 2016-06-13 17:25
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用