go - 我正在尝试使用 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>}
解决方案
推荐阅读
- php - PHP (Codeigniter) - 工作日和周末价格不同
- angular - 升级到 Angular v9 后程序不包含 main.server.ngfactory.ts
- java - JavaFX EventHandler 中此 InvocationTargetException 的原因?
- python-3.x - Windows Python Selenium Webdriver 只能在无头 Chrome 中运行,不能在带有 UI 的 Chrome 中运行
- machine-learning - 具有不同 GPU 的变形金刚的多 GPU 训练
- excel - CurrentRegion excel VBA问题
- python - 带有类型提示的 cython 纯 python
- keyboard - 检测 VB6 中存在的键盘
- reactjs - Draft-js:使用不可编辑的实体组件丢失光标
- windows - 如何获取活动连接上的 DNS 默认网关 IP 并使用 Windows 10 批处理文件将其设置为变量?