Created
March 10, 2019 14:59
-
-
Save wemgl/0558ebeed2f6e02cdabeb8edf192a87c to your computer and use it in GitHub Desktop.
Example of testing the index handler for simple server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func TestIndex(t *testing.T) { | |
req, err := http.NewRequest(http.MethodGet, "/", nil) | |
if err != nil { | |
t.Fatalf("TestIndex: couldn't create HTTP GET request: %v", err) | |
} | |
rec := httptest.NewRecorder() | |
index().ServeHTTP(rec, req) | |
res := rec.Result() | |
defer func() { | |
err := res.Body.Close() | |
if err != nil { | |
t.Fatalf("TestIndex: couldn't close response body: %v", err) | |
} | |
}() | |
if res.StatusCode != http.StatusOK { | |
t.Errorf("TestIndex: got status code %v, but want: %v", res.StatusCode, http.StatusOK) | |
} | |
body, err := ioutil.ReadAll(res.Body) | |
if err != nil { | |
t.Fatalf("TestIndex: could not read response body: %v", err) | |
} | |
if len(string(body)) == 0 { | |
t.Errorf("TestIndex: unexpected empty response body") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment