http - 如何在go中测试http请求

标签 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

最佳答案

你可以使用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,因此它不能是一个常量(您可能只想将其作为参数传递)。您可以在 http.HandlerFunc 或基于响应编写测试断言。

关于http - 如何在go中测试http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52707948/

相关文章:

ruby - Autotest、Shoulda、Ruby - 设置?

php - 在 php 中将 float 组作为 HTTP POST 请求发送

c# - 通过递归遍历所有属性的属性来比较两个对象?

python-3.x - python3 http.server 记录如何

go - 使用 Gin 测试 CORS 中间件

go - 将方法作为参数传递给结构实例

go - 使用supervisord运行Golang程序时无法识别GOPATH

testing - 如何在 go test 中检查日志/输出?

javascript - 复制 $rootScope

Android JSON POST 与 OKHTTP