【发布时间】: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
【问题讨论】:
标签: go httprequest