gpt4 book ai didi

unit-testing - 正确使用 httptest 模拟响应

转载 作者:IT王子 更新时间:2023-10-29 01:52:36 25 4
gpt4 key购买 nike

我有一些看起来像这样的东西:

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 包来模拟这个请求...我通读了 the docs这很有帮助 SO Answer但我还是卡住了。

最佳答案

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

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

关于unit-testing - 正确使用 httptest 模拟响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37795629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com