ant0ine / go-json-rest-examples

Examples for go-json-rest
http://ant0ine.github.io/go-json-rest/
MIT License
195 stars 52 forks source link

How to test go-json-rest routes? #1

Open phstc opened 10 years ago

phstc commented 10 years ago

Hey @ant0ine

How do you usually test your routes (status code, body etc)? A go-json-rest route expects w *rest.ResponseWriter and r *rest.Request, but using NewResquest and NewRecorder we get httptest.ResponseRecorder and http.Request.

// message.go
/// ...
func main() {
    api := Api{}
    api.initDB()

    defer api.closeDB()

    handler := rest.ResourceHandler{
        EnableRelaxedContentType: true,
    }

    handler.SetRoutes(
        rest.RouteObjectMethod("POST", "/api/messages", &api, "CreateMessage"),
    )

    log.Println("Starting in development on http://0.0.0.0:8080")

    http.ListenAndServe(":8080", &handler)
}

func (api *Api) CreateMessage(w *rest.ResponseWriter, r *rest.Request) {
    w.WriteJson("ok")
}
func TestStatusCode(t *testing.T) {
  request, _ := http.NewRequest("POST", "http://localhost:8080/api/messages", nil)
  response := httptest.NewRecorder()

  api := main.Api{}

  // api.CreateMessage(response, request)

  if response.Code != http.StatusOK {
    t.Fatalf("Non-expected status code%v:\n\tbody: %v", "200", response.Code)
  }
}
ant0ine commented 10 years ago

Hi @phstc

I wrote some route tests, and realizing the I was writing the same boilerplate code over and over again, I factorized that into https://github.com/ant0ine/go-json-rest/blob/master/test/util.go

You can see some tests using this here: https://github.com/ant0ine/go-json-rest/blob/master/handler_test.go

Hope that helps.

Antoine