go-json-rest
go-json-rest copied to clipboard
ResponseRecorder for easy to unit test handler function
I created ResponseRecorder for unit test handler function. I think it useful when create handler without settings App before.
This is example
package test
import (
"net/http"
"testing"
"github.com/ant0ine/go-json-rest/rest"
)
func helloHandler(w rest.ResponseWriter, r *rest.Request) {
w.WriteJson(map[string]string{"hello": r.PathParam("name")})
}
func TestRecorder(t *testing.T) {
var (
recorder = NewRecorder()
req, _ = http.NewRequest("GET", "http://localhost/hello/yourname", nil)
r = &rest.Request{
Request: req,
PathParams: map[string]string{"name": "yourname"},
}
)
helloHandler(recorder, r)
if recorder.Code != http.StatusOK {
t.Error("expect status 200")
}
if recorder.Body.String() != `{"hello":"yourname"}` {
t.Error("expect body", recorder.Body.String())
}
}
please review Thanks.
Hi @wingyplus, thanks for your pull request!
What is the benefit of this ResponseWriter comparing to the recorder already provided here: https://github.com/ant0ine/go-json-rest/blob/master/rest/test/util.go ?
@ant0ine our team have a multiple route (about 5 uri per feature, we have 15 features :D ), Recored in util.go must be make http.Handler before. I think it not make sense to load all route for testing one logic in single route handler function.
ResponseRecorder make it for test logic in handler function without setup http.Handler before (like use http.ResponseRecorder to test handler function in net/http example).
Thanks
@ant0ine did you have any comment about this feature?
:+1: for this