Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test http calls in go

I have the following code:

// 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
}

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

like image 323
gautam Avatar asked Mar 06 '23 22:03

gautam


1 Answers

Take a look here:

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

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

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
}
like image 78
eugenioy Avatar answered Mar 09 '23 07:03

eugenioy