如何模拟 http.Head()

How to mock http.Head()

我正在研究 https://github.com/golang/example/tree/master/outyet. The test file does not cover the case where http.Head(url) returns an error. I would like to extend the unit tests to cover the if statement where the error is logged (https://github.com/golang/example/blob/master/outyet/main.go#L100) 的早期示例项目。我想模拟 http.Head(),但我不确定该怎么做。如何做到这一点?

http.Head 函数只是在默认 HTTP 客户端(显示为 http.DefaultClient)上调用 Head method。通过替换测试中的默认客户端,您可以更改这些标准库函数的行为。

特别是,您需要一个设置自定义传输的客户端(任何实现 http.RoundTripper 接口的对象)。类似于以下内容:

type testTransport struct{}

func (t testTransport) RoundTrip(request *http.Request) (*http.Response, error) {
    # Check expectations on request, and return an appropriate response
}

...

savedClient := http.DefaultClient
http.DefaultClient = &http.Client{
    Transport: testTransport{},
}

# perform tests that call http.Head, http.Get, etc

http.DefaultClient = savedClient

您还可以使用此技术通过从传输而不是 HTTP 响应返回错误来模拟网络错误。