Skip to content

Instantly share code, notes, and snippets.

@wemgl
Created March 10, 2019 14:59
Show Gist options
  • Save wemgl/0558ebeed2f6e02cdabeb8edf192a87c to your computer and use it in GitHub Desktop.
Save wemgl/0558ebeed2f6e02cdabeb8edf192a87c to your computer and use it in GitHub Desktop.
Example of testing the index handler for simple server
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