如何在Go中测试HTTP请求

时间:2018-10-08 18:14:02

标签: http go testing

我有一个go包,它基本上是python API的包装。我不确定如何测试http.NewRequest,client.Do和ioutil.ReadAll的错误。我知道httptest存在,但我还很陌生,因此无法正常工作。任何帮助将不胜感激!

func DeleteApp(platform string, hostname string, header string) error {

if platform == "" || hostname == "" {
    fmt.Printf("[DELETE APP] Platform and hostname can not be empty strings")
    return errors.New("[DELETE APP] Platform and hostname can not be empty strings")
}
url := fmt.Sprintf(baseURL+"delete-app/%s/%s", platform, hostname)

// Create client & set timeout
client := &http.Client{}
client.Timeout = time.Second * 15

// Create request
req, err := http.NewRequest("DELETE", url, nil)
if err != nil {
    fmt.Printf("[DELETE APP] Could not create request : %v", err)
    return err
}

//check for optional header
if header != "" {
    req.Header.Add("X-Fields", header)
}

// Fetch Request
resp, err := client.Do(req)
if err != nil {
    fmt.Printf("[DELETE APP] Could not fetch request : %v", err)
    return err
}
defer resp.Body.Close()

//Read Response Body
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
    fmt.Printf("[DELETE APP] Could not read response body : %v", err)
    return err
}

fmt.Println("response Status : ", resp.Status)
fmt.Println("response Headers : ", resp.Header)
fmt.Println("response Body : ", string(respBody))

return nil

}

1 个答案:

答案 0 :(得分:2)

您可以使用httptest.NewServer

func TestDeleteApp(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "Hello, client")
    }))
    defer ts.Close()

    baseURL = ts.URL + "/"

    DeleteApp("platform", "hostname", "header")

}

这将重写全局baseURL,因此它不能是const(您可能只想将其作为参数传递)。您可以在http.HandlerFunc中或根据响应编写测试断言。