unit-testing - 如何模拟 http.Head()

标签 unit-testing go mocking

我正在研究来自 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/

相关文章:

java - 单元测试中的 Spring Boot 数据源

c# - 在 Moq Callback() 调用中设置变量值

python - 在 Python 中模拟导入的模块

unit-testing - py.test : dump stuck background threads at the end of the tests

c# - 使用 NUnit,我可以确定哪些测试先于当前运行的测试吗?

xml - 如何在 Golang 中将 []byte XML 转换为 JSON 输出

hash - Golang 使用 MD5 编码字符串 UTF16 little endian 和哈希

java - Controller 测试模拟装置

objective-c - 如何在 Xcode 3 中调试单元测试?

amazon-web-services - Lambda API 网关 POST 参数