我正在模拟服务器来测试我的应用程序。我用 Golang 和 Gin 构建了模拟服务器。对于成功案例来说效果很好。
但我想测试的情况之一是当服务器没有响应时应用程序的行为方式。我希望当应用程序发送具有特定值的请求时,模拟服务器不应应答。但我没能用杜松子酒实现这一目标。
我尝试让 Gin 处理函数不设置上下文,但 Gin 仍然发送一个空的 200 OK。没有处理程序的 router.GET 也会回复一个空的 200OK。我检查了广泛的 Gin 文档,但找不到答案。
如何模拟从未收到响应的服务器或网络错误?
当服务器没有返回任何内容时,有两种情况(据我所知)
从问题来看,我们正在寻找模型#2。
出于测试目的,模拟连接重置的一种方法是从
http.RoundTripper
内部返回错误到测试中使用的 http.Client
。
http.Client
的内部是一个http.RoundTripper
,它是一个需要以下方法的接口:
RoundTrip(*Request) (*Response, error)
根据文档:
RoundTrip must return err == nil if it obtained
a response, regardless of the response's HTTP status code.
A non-nil err should be reserved for failure to obtain a
response.
以下是如何执行此操作的示例:
type connectionResetTransport struct {}
func (c *connectionResetTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return nil, fmt.Errorf("connection reset")
}
// usage
connectionResetClient := http.Client{
Transport: &connectionResetTransport{},
}
connectionResetClient.Get("http://localhost:8080")
// or use connectionResetClient as the http.Client in whatever system you're trying to test