首页 > 解决方案 > 我正在尝试使用 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>}

标签: gonet-httpmux

解决方案


推荐阅读