如何在Go中测试HTTP调用 [英] How to test http calls in go

查看:48
本文介绍了如何在Go中测试HTTP调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

// 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包.

I'd like to write the tests for this, but I am not sure how to use httptest package .

推荐答案

在这里看看:

https://golang.org/pkg/net/http/httptest/# example_Server

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

Basically, you can create a new "mock" http server using httptest.NewServer function.

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

You can have your mock server return whatever response you need from the test, and you can also have your mock server store the request that your HTTPPost function made in order to assert over it.

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
}

这篇关于如何在Go中测试HTTP调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆