亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么這個咕嚕咕咕HTTP響應程序返回錯誤的調用次數?

為什么這個咕嚕咕咕HTTP響應程序返回錯誤的調用次數?

Go
一只斗牛犬 2022-09-26 17:33:45
我正在為我的 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響應器中傳遞指針。


查看完整回答
反對 回復 2022-09-26
  • 1 回答
  • 0 關注
  • 101 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號