Unit testing 如何在go中测试http调用

Unit testing 如何在go中测试http调用,unit-testing,go,Unit Testing,Go,我有以下代码: // HTTPPost to post json messages to the specified url func HTTPPost(message interface{}, url string) (*http.Response, error) { jsonValue, err := json.Marshal(message) if err != nil { logger.Error("Cannot Convert to JSON: ", e

我有以下代码:

// HTTPPost to post json messages to the specified url
func HTTPPost(message interface{}, url string) (*http.Response, error) {
    jsonValue, err := json.Marshal(message)
    if err != nil {
        logger.Error("Cannot Convert to JSON: ", err)
        return nil, err
    }
    logger.Info("Calling http post with url: ", url)
    resp, err := getClient().Post(url, "application/json", bytes.NewBuffer(jsonValue))
    if err != nil {
        logger.Error("Cannot post to the url: ", url, err)
        return nil, err
    }
    err = IsErrorResp(resp, url)
    return resp, err
}
我想为此编写测试,但我不确定如何使用httptest包

看看这里:

基本上,您可以使用
httptest.NewServer
函数创建一个新的“模拟”http服务器

您可以让模拟服务器返回测试中需要的任何响应,还可以让模拟服务器存储
HTTPPost
函数发出的请求,以便对其进行断言

func TestYourHTTPPost(t *testing.T){

    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, `response from the mock server goes here`)
        // you can also inspect the contents of r (the request) to assert over it
    }))
    defer ts.Close()

    mockServerURL = ts.URL

    message := "the message you want to test"

    resp, err := HTTPPost(message, mockServerURL)

    // assert over resp and err here
}

网络上有很多例子,你试过什么吗?