我有一些看起来像这样的东西: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)
- 1 回答
- 0 关注
- 229 浏览
添加回答
举报
0/150
提交
取消
