|
|
|
|
|
by jrockway
1983 days ago
|
|
I don't think it's the worst thing in the world if you test your http.Handler implementation: w := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/foo", nil)
ServeHTTP(w, req)
if got, want := w.Code, http.StatusOK; got != want {
t.Errorf("get /foo: status:\n got: %v\n want: %v", got, want)
}
if got, want := w.Body.String(), "it worked"; got != want {
t.Errorf("get /foo: body:\n got: %v\n want: %v", got, want)
}
It leaves very little to the imagination as to whether or not ServeHTTP works, which is nice.Complexity comes from generating requests and parsing the responses, and that is what leads to the desire to factor things out -- test the functions with their native data types instead of http.Request and http.Response. I think most people choose to factor things out to make that possible, but in the simplest of simple cases, many people just use httptest. It gets the job done. |
|
The problem I've seen is over-dependence on writing unit tests with mocks instead of biting the bullet and properly testing all the boundaries. I have seen folk end up with 1000+ tests, of which most are useless because the mocks make far too many assumptions, but are necessary because of the layer coupling.
This was mostly in Node though, where mocking the request/response gets done inconsistently, per framework. Go might have better tooling in that regard, and maybe that sways the equation a bit. IMO there's still merit to decoupling if there's any feasibility of e.g. migrating to GraphQL or another protocol without having to undergo an entire re-write.