【问题标题】:Why does this GoLang Mock HTTP responder return the wrong number of times it was called?为什么这个 GoLang Mock HTTP 响应程序返回错误的调用次数?
【发布时间】:2021-08-28 08:54:28
【问题描述】:

我正在为发出 HTTP 请求的 Go 应用程序编写测试用例。 为了模拟来自远程主机的响应,我创建了这个类 stringProducer

type stringProducer struct {
    strings   []string
    callCount int
}

func (s *stringProducer) GetNext() string {
    if s.callCount >= len(s.strings) {
        panic("ran out of responses")
    }
    s.callCount++
    fmt.Println("s.CallCount = ", s.callCount)
    return s.strings[s.callCount-1]
}

func mockHTTPResponder(producer stringProducer) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte(producer.GetNext()))
    })
}

这是我在主函数中的调用方式:

func main() {
    producer := stringProducer{
        strings: []string{"Hello World!"},
    }

    srv := httptest.NewServer(mockHTTPResponder(producer))
    if producer.callCount != 0 {
        panic("callCount is not 0")
    }

    var buf io.ReadWriter
    req, _ := http.NewRequestWithContext(context.Background(), http.MethodGet, fmt.Sprintf("%s/path/to/something", srv.URL), buf)

    newClient := http.Client{}

    newClient.Do(req)

    if producer.callCount != 1 {
        panic("callCount is not 1")
    }
}

在此代码中,当发出 HTTP 请求时,它会转到上面的响应者,该响应者会以一些预先指定的文本进行响应。它还会使计数器stringProducer.callCount 增加1。

从下面的程序输出中,您可以看到它打印了一行,显示 callCount 已递增到 1。但是,当我检查相同的值时,它不是 1。它是零。为什么?以及如何解决这个问题?

s.CallCount =  1
panic: callCount is not 1

goroutine 1 [running]:
main.main()
    /tmp/sandbox3935766212/prog.go:50 +0x118

前往游乐场链接:https://play.golang.org/p/mkiJAfrMdCw

【问题讨论】:

    标签: go httprequest


    【解决方案1】:

    您在 mockHTTPResponder 中通过值 stringProducer 传递。当您这样做时,您会在 mockHTTPResponder 中获得该变量的副本。并且在该副本上进行了以下所有更改(原始 stringProducer 保持不变):

    func mockHTTPResponder(producer stringProducer) http.Handler { // <- producer is a copy of the original variable
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            w.WriteHeader(http.StatusOK)
            w.Write([]byte(producer.GetNext()))  // <- s.callCount++ on the copy
        })
    }
    

    mockHTTPResponder 中传递一个指针。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 2014-05-09
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多