我正在尝试在Go库中测试HTTP请求。使调用的对象通过依赖注入接受HTTP客户端对象,因此在我的测试中,我正在模拟HTTP客户端,如下所示:
func TestMyObject(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
fmt.Fprintln(w, mockJSONResponse)
}))
defer server.Close()
// Make a transport that reroutes all traffic to the example server
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(server.URL)
},
}
// Make a http.Client with the transport
httpClient := &http.Client{Transport: transport}
// I am passing the httpClient to my object
}
以下是在我的对象中进行HTTP请求的方式:
// Make - makes a prepared HTTP request
func (ir *MyObject) Make() *http.Response {
if ir.Err != nil {
return nil
}
ir.resp, ir.Err = ir.Client.Do(ir.req)
runtime.SetFinalizer(ir, func(ir *MyObject) {
ir.resp.Body.Close()
})
ir.logReqRes()
ir.checkErrorResponse()
return ir.resp
}
我收到了nil指针解除引用错误:
panic: runtime error: invalid memory address or nil pointer dereference [recovered]
panic: runtime error: invalid memory address or nil pointer dereference
在这个函数中(我试图记录响应):
// Logs request and response
func (ir *MyObject) logReqRes() {
log.Print("AAAAAAA")
log.Print(ir.resp)
log.Print("AAAAAAA")
if reqInfo, err := httputil.DumpRequest(ir.req, true); err == nil {
log.Print("Logging request:")
log.Print(string(reqInfo))
}
if respInfo, err := httputil.DumpResponse(ir.resp, true); err == nil {
log.Print("Logging response:")
log.Print(string(respInfo))
}
}
如您所见,ir.resp由于某种原因是零。有什么想法吗?
答案 0 :(得分:0)
确定。我发现了一个问题。更好地记录错误实际上表明我的错误很简单。
我将此作为模拟HTTP客户端的URL传递:
host/api/v1/tokens/
导致此错误:
Post host/api/v1/tokens/: unsupported protocol scheme
显然,即使您使用测试服务器,URL也必须包含正确的HTTP方案(http://)。