Testing

Route Tests

Assert route behavior with httptest and the real application handler.

By Guillermo Alvarez - Published Updated

Use the real handler

Build the same handler that production uses:

func application() http.Handler {
    return appinit.App()
}

Then issue requests with httptest:

request := httptest.NewRequest(http.MethodGet, "/posts", nil)
response := httptest.NewRecorder()

application().ServeHTTP(response, request)

if response.Code != http.StatusOK {
    t.Fatalf("status = %d", response.Code)
}

Test path parameters

Route parameters should reach the selected action:

request := httptest.NewRequest(http.MethodGet, "/posts/hello-golazy", nil)
response := httptest.NewRecorder()

application().ServeHTTP(response, request)

if !strings.Contains(response.Body.String(), "Hello GoLazy") {
    t.Fatal("post body was not rendered")
}

Test methods

Unsupported methods should return method errors:

request := httptest.NewRequest(http.MethodPost, "/posts/hello-golazy", nil)
response := httptest.NewRecorder()

application().ServeHTTP(response, request)

if response.Code != http.StatusMethodNotAllowed {
    t.Fatalf("status = %d", response.Code)
}