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

Why does this GoLang Mock HTTP responder return the wrong number of times it was called?

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

去游乐场 link 这里: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.

中传递一个指针