为什么这个GoLang Mock HTTP响应器返回错误的调用次数?



我正在为我的Go应用程序编写HTTP请求的测试用例。为了模拟来自远程主机的响应,我创建了这个类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()))
})
}

下面是我在main函数中调用它的方式:

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

Go Playground链接在这里:https://play.golang.org/p/mkiJAfrMdCw

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内部传递一个指针。

最新更新