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

You may create and use an http.Request forged by you, which deliberately returns an error when reading its body. You don’t necessarily need a whole new request, a faulty body is enough (which is an io.ReadCloser).

Simplest achieved by using the httptest.NewRequest() function where you can pass an io.Reader value which will be used (wrapped to be an io.ReadCloser) as the request body.

Here’s an example io.Reader which deliberately returns an error when attempting to read from it:

type errReader int

func (errReader) Read(p []byte) (n int, err error) {
    return 0, errors.New("test error")
}

Example that will cover your error case:

func HandlePostRequest(w http.ResponseWriter, r *http.Request) {
    defer r.Body.Close()
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Printf("Error reading the body: %v\n", err)
        return
    }
    fmt.Printf("No error, body: %s\n", body)
}

func main() {
    testRequest := httptest.NewRequest(http.MethodPost, "/something", errReader(0))
    HandlePostRequest(nil, testRequest)
}

Output (try it on the Go Playground):

Error reading the body: test error

See related question if you would need to simulate error reading from a response body (not from a request body): How to force error on reading response body

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)