I've written http client wrapper in go and I need to test it thoroughly. I'm reading the response body with ioutil.ReadAll within the wrapper. I'm having a bit of trouble figuring out how I can force a read from the response body to fail with the help of httptest.
package req
func GetContent(url string) ([]byte, error) {
response, err := httpClient.Get(url)
// some header validation goes here
body, err := ioutil.ReadAll(response.Body)
defer response.Body.Close()
if err != nil {
errStr := fmt.Sprintf("Unable to read from body %s", err)
return nil, errors.New(errStr)
}
return body, nil
}
I'm assuming I can set up a fake server as such:
package req_test
func Test_GetContent_RequestBodyReadError(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
ts := httptest.NewServer(http.HandlerFunc(handler))
defer ts.Close()
_, err := GetContent(ts.URL)
if err != nil {
t.Log("Body read failed as expected.")
} else {
t.Fatalf("Method did not fail as expected")
}
}
I'm assuming I need to modify the ResposeWriter. Now, is there any way for me to modify the responseWriter and thereby force the ioutil.ReadAll in the wrapper to fail?
I realize that you seem to think it's a duplicate of this post and while you may believe so or it might be, just marking it as a duplicate doesn't really help me. The code provided in the answers in the "duplicate" post makes very little sense to me in this context.