As title, when to use httptest.Server and httptest.ResponseRecorder?
It seems to me that I can also test my handlers to return correct response using httptest.Server. I can simply start a httptest.Server given with my implementation of handlers, then do validations on the response's body.
Please correct if I'm wrong, I am learning Go + TDD
httptest. NewRequest provides a convenience wrapper around http. NewRequest so you don't have to check the error making a Request object. Below that httptest. NewRecorder makes a recorder that the HTTP handler writes to as its http.
As mentioned earlier, httptest, or net/http/httptest in full, is a standard library for writing constructive and unit tests for your handlers. It provides ways to mock requests to your HTTP handlers and eliminates the need of having to run the server.
type ResponseWriter interface { Header() Header Write([]byte) (int, error) WriteHeader(statusCode int) } The Golang net/http Handler interface has serveHTTP method that takes the Response Writer interface as input and this allows the Golang HTTP Server to construct HTTP Response.
When you just want to check, if your http.Handler
does what it should, you don't need to use httptest.Server
. Just call your handler with an httptest.ResponseRecorder
instance and check the output as in the example.
The possible uses of httptest.Server
are numerous, so here are just a couple that come to my mind:
If your code depends on some external services and APIs, you can use a test server to emulate them. (Although I personally would isolate all code dealing with external data sources and then use them through interfaces, so that I could easily create fake objects for my tests.)
If you work on a client-server application, you can use a test server to emulate the server-side when testing the client-side.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With