英文:
How to mock http.Head()
问题
我正在学习来自https://github.com/golang/example/tree/master/outyet的outyet示例项目。测试文件没有覆盖http.Head(url)
返回错误的情况。我想扩展单元测试以覆盖记录错误的if语句(https://github.com/golang/example/blob/master/outyet/main.go#L100)。我想模拟http.Head()
,但我不确定如何做到这一点。应该如何实现?
英文:
I'm studying the outyet example project from 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). I would like to mock http.Head()
, but I'm not sure how to do this. How can this be done?
答案1
得分: 4
http.Head
函数只是在默认的HTTP客户端(作为http.DefaultClient
公开)上调用Head
方法。通过替换测试中的默认客户端,您可以更改这些标准库函数的行为。
特别是,您需要一个设置自定义传输(任何实现http.RoundTripper
接口的对象)的客户端。类似以下代码:
type testTransport struct{}
func (t testTransport) RoundTrip(request *http.Request) (*http.Response, error) {
// 检查请求的期望,并返回适当的响应
}
...
savedClient := http.DefaultClient
http.DefaultClient = &http.Client{
Transport: testTransport{},
}
// 执行调用http.Head、http.Get等的测试
http.DefaultClient = savedClient
您还可以使用此技术通过从传输中返回错误而不是HTTP响应来模拟网络错误。
英文:
The http.Head
function simply calls the Head
method on the default HTTP client (exposed as http.DefaultClient
). By replacing the default client within your test, you can change the behaviour of these standard library functions.
In particular, you will want a client that sets a custom transport (any object implementing the http.RoundTripper
interface). Something like the following:
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
You could also use this technique to mock network errors by returning an error from your transport rather than an HTTP response.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论