我正在研究来自 https://github.com/golang/example/tree/master/outyet 的示例项目. test file不包括 http.Head(url)
的情况返回错误。我想扩展单元测试以涵盖记录错误的 if 语句 ( https://github.com/golang/example/blob/master/outyet/main.go#L100 )。我想模拟 http.Head()
,但我不确定该怎么做。如何做到这一点?
最佳答案
http.Head
函数只是调用 Head
method在默认 HTTP 客户端上(显示为 http.DefaultClient
)。通过替换测试中的默认客户端,您可以更改这些标准库函数的行为。
特别是,您需要一个设置自定义传输的客户端(任何实现 http.RoundTripper
接口(interface)的对象)。类似于以下内容:
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 响应返回错误来模拟网络错误。
关于unit-testing - 如何模拟 http.Head(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30413537/