我正在為我的 Go 應用程序編寫測試用例,以發出 HTTP 請求。為了模擬來自遠程主機的響應,我創建了此類字符串轉換器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請求時,它會轉到上面的響應者,該響應程序使用一些預先指定的文本進行響應。它還會導致計數器遞增 1。stringProducer.callCount從下面的程序輸出中,您可以看到它打印了一行,顯示 callCount 已遞增到 1。但是,當我檢查相同的值時,它不是1。它是零。為什么?如何解決這個問題?s.CallCount = 1panic: callCount is not 1goroutine 1 [running]:main.main() /tmp/sandbox3935766212/prog.go:50 +0x118去游樂場鏈接在這里: https://play.golang.org/p/mkiJAfrMdCw
1 回答

慕斯709654
TA貢獻1840條經驗 獲得超5個贊
在模擬HTTPResponder中傳遞值字符串。當您執行此操作時,您將獲得模擬HTTP響應器中變量的副本。并且對該副本進行了以下所有更改(原始字符串制作器保持不變):
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
})
}
在模擬HTTP響應器中傳遞指針。
- 1 回答
- 0 關注
- 101 瀏覽
添加回答
舉報
0/150
提交
取消