Skip to content

Instantly share code, notes, and snippets.

@gufranmirza
Created July 7, 2018 19:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gufranmirza/66558c0b94cee7af61c09cd595d8c2bf to your computer and use it in GitHub Desktop.
Save gufranmirza/66558c0b94cee7af61c09cd595d8c2bf to your computer and use it in GitHub Desktop.
func TestRouterForNonExistentRoute(t *testing.T) {
r := newRouter()
mockServer := httptest.NewServer(r)
// Most of the code is similar. The only difference is that now we make a
//request to a route we know we didn't define, like the `POST /hello` route.
resp, err := http.Post(mockServer.URL+"/hello", "", nil)
if err != nil {
t.Fatal(err)
}
// We want our status to be 405 (method not allowed)
if resp.StatusCode != http.StatusMethodNotAllowed {
t.Errorf("Status should be 405, got %d", resp.StatusCode)
}
// The code to test the body is also mostly the same, except this time, we
// expect an empty body
defer resp.Body.Close()
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.Fatal(err)
}
respString := string(b)
expected := ""
if respString != expected {
t.Errorf("Response should be %s, got %s", expected, respString)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment