如何解决我正在尝试使用mux和httptest在Golang中测试REST Api客户端
在这里,我试图通过将apiOutput写入http.ResponseWriter中来为REST客户端编写测试,但是我总是收到{nil nil}作为apiResponse。
有人可以帮助我指出错误吗?
func Test_Do(t *testing.T) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
config := NewClientConfig()
config.BaseURL = server.URL
client,err := NewClient(config)
if err != nil {
t.Fatal(err)
}
apiResponse := struct {
Id string `json:"id"`
Error error `json:"error"`
Data interface{} `json:"data"`
}{}
apiOutput := []byte(`{
"id":"1","error":nil,"data":[{"IP": "1.2.2.3"}]}`)
mux.HandleFunc("/api/v1/hosts",func(w http.ResponseWriter,r *http.Request) {
w.Header().Set("Content-Type","application/json")
w.Write(apiOutput)
})
t.Run("Get Host Details",func(t *testing.T) {
req,err := client.MakeGetRequest(http.MethodGet,"/api/v1/hosts",nil)
if err != nil {
t.Fatal(err)
}
resp,err1 := client.Do(req,&apiResponse)
if err1 != nil {
t.Fatalf("failed with statusCode: %d,error: %s",resp.StatusCode,err1)
}
if apiResponse.Id != "1" || apiResponse.Error != nil {
t.Errorf("Client.Do() problem unmarshaling problem: got %#v",apiResponse)
}
fmt.Printf("%v",apiResponse)
})
}
func (c *Client) Do(req *http.Request,v interface{}) (*http.Response,error) {
resp,err := c.HTTPClient.Do(req)
if err != nil {
return nil,err
}
defer resp.Body.Close()
if errorResponse := c.CheckResponse(resp); errorResponse != nil {
return resp,errorResponse
}
if v != nil {
if w,ok := v.(io.Writer); ok {
io.Copy(w,resp.Body)
} else {
decErr := json.NewDecoder(resp.Body).Decode(v)
if decErr == io.EOF {
decErr = nil // ignore EOF errors caused by empty response body
}
if decErr != nil {
err = decErr
}
}
}
return resp,err
}
输出:
Test_Do/Get_Host_Details: clients_test.go:269: Client.Do() problem unmarshaling problem: got struct { Id string "json:\"id\""; Error error "json:\"error\""; Data interface {} "json:\"data\"" }{Id:"",Error:error(nil),Data:interface {}(nil)}
{ <nil> <nil>}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。