vendredi 21 juin 2019

How do I test an error on reading from a response body?

I have this method

func SendRequest(url, method string, requestBody io.Reader, headers *http.Header) (*[]byte, int, error) {

which sends HTTP request to given url and responds with response bytes, status code and error if present.

I have written test using http/httptest

func TestSendRequest(t *testing.T) {
    ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "testing send request")
    }))
    defer ts.Close()

    bytes, code, err := SendRequest(ts.URL, http.MethodGet, nil, nil)

    assert.Nil(t, err)
    assert.EqualValues(t, "testing send request", string(*bytes))
    assert.EqualValues(t, http.StatusOK, code)
} // TestSendRequest

This test is for successful connection.

I want to write test for a failure case. Inside the SendRequest() method, I have

respBody, err := ioutil.ReadAll(resp.Body)

Is it possible to write a handler method that would give error (io.EOF error)

Aucun commentaire:

Enregistrer un commentaire