为了账号安全,请及时绑定邮箱和手机立即绑定

正确使用 httptest 来模拟响应

正确使用 httptest 来模拟响应

Go
泛舟湖上清波郎朗 2022-01-17 18:07:03
我有一些看起来像这样的东西: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但我仍然卡住了。
查看完整描述

1 回答

?
慕莱坞森

TA贡献1810条经验 获得超4个赞

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

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


查看完整回答
反对 回复 2022-01-17
  • 1 回答
  • 0 关注
  • 229 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号