【问题标题】:Correctly using httptest to mock responses正确使用 httptest 来模拟响应
【发布时间】:2016-06-14 01:25:46
【问题描述】:

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

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,但我仍然卡住了。

【问题讨论】:

    标签: unit-testing go


    【解决方案1】:

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

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

    【讨论】:

    • 我错过了这个关键点,重新阅读文档/示例这很有意义。
    猜你喜欢
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多