Hi!
What are your opinions about testing an HTTP handler by running its function ServeHTTP directly and testing it by using an httptest.Server? When should I use each?
I created some sample code which tests the handler in file.go using the two approaches I mentioned:
file.go: https://play.golang.org/p/asn84yLhQC file_test.go: https://play.golang.org/p/T3ydynj33K
Thanks!
评论:
mwholt:
benbjohnson:Use an httptest.Server if you need to test a client. Otherwise, if you're testing your handler function, just call it directly.
dchapes:I almost always use httptest.Server. It doesn't add much overhead and it lets your requests go through the full server lifecycle rather than trying to construct the http.Request yourself.
to construct the
http.Request
yourselfThat's what
httptest.NewRequest
andhttptest.ResponseRecorder
are for. Using them is simpler thanhttptest.Server
+http.Client
for doing all the non end-to-end HTTP testing of your handlers (which should usually be the majority of the tests).
