我正在尝试使用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 (将#修改为@)