Trigger http client error for testing with httptest

Solution for Trigger http client error for testing with httptest
is Given Below:

I have a simple function which takes a URL and fetches the response:

func getUrl(url string) (string, error) {
    var theClient = &http.Client{Timeout: 12 * time.Second}

    resp, err := theClient.Get(url)
    if err != nil {
        return "", err
    }
    defer r.Body.Close()

    body, readErr := ioutil.ReadAll(resp.Body)
    if readErr != nil {
        return "", readErr
    }

    return string(body), nil
}

Now, I want to trigger an error on the theClient.Get(url) line but I don’t know how to. I can trigger an error on the ReadAll() line, by returning no response but with content-length:2.

How can I trigger an error on the theClient.Get(url) line for my unit test?

func TestGetUrl(t *testing.T) {
    server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Length", "2")
    }))
    defer server.Close()

    gotContent, gotErr := getUrl(server.URL)
    wantErr := "unexpected EOF"

    if gotErr == nil || gotErr.Error() != wantErr {
        t.Errorf("got err %v; wanted %s", gotErr, wantErr)
    }
}

Easiest way is to simply pass an invalid URL:

_, err := http.Get("clearly not a valid url")
fmt.Println("Got error:", err != nil) // Got error: true

Another option is to make it timeout by sleeping in your httptest.Server handler, but that doesn’t seem like a very nice idea (but you will be able to assert that it was called in the first place).