The httptest
package provides utilities for HTTP testing:
- Test server handler logic by mocking the request.
- Test client logic by mocking the server handler.
For server handler testing, you need ResponseRecorder
object to record the
http.ResponseWriter’s mutations, plus httptest.NewRequest
and pass them into
the server handler for (w http.ResponseWriter, r *http.Request)
.
For client logic testing, you need to mock specific server handler or
even entire server, using the httptest.NewServer
Object or other server types.
From the main page, it provides types for:
- ResponseRecorder
- NewTLSServer
- Server
- Server(HTTP2)
For client logic testing, if you only set up one handler and call it repeatedly, it returns the same response. If you do want to have different response when you call mock server, here is the example, I enrich it by adding more in handlers.
1 | package main |