Go Code Examples: httptest.NewServer
Imagine you’re asked to create an API client program, and you want to test your code. This is an example to use httptest
package for HTTP client code testing.
Preparation
The test target has the following interface.
type Client struct {
cli *http.Client
URL string
}// Get calls GET request to c.URL and returns the response as string
func (c *Client) Get() (string, error) {...}
Example
This is the entire code.
func TestGet(t *testing.T) {
want := "Success!"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte(want))
}))
defer srv.Close() sut := &Curl{
Client: srv.Client(),
URL: srv.URL,
} got, err := sut.Get(map[string]string{})
if err != nil {
t.Errorf("Unexpected error on request: %s", err)
}
if got != want {
t.Errorf("want %s, got %s", want, got)
}
}
Call httptest.NewServer
We expect Get to return the http body from the server as string. First, start up a testing server, and return the expected response inside the handler.
want := "Success!"
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
w.Write([]byte(want))
}))
defer srv.Close()
(Don’t forget to close the test server.)
Create a client with the server properties
http.Server struct has Client
and URL
properties. Use these values to instantiate client.
sut := &Curl{
Client: srv.Client(),
URL: srv.URL,
}
Check the response
Finally, call the test target method and check the returned value if it matches with what we want.
got, err := sut.Get(map[string]string{})
if err != nil {
t.Errorf("Unexpected error on request: %s", err)
}
if got != want {
t.Errorf("want %s, got %s", want, got)
}
Assert inside the handler
You can write assertions inside the handler like this.
handler = func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
t.Errorf("want %s, got %s", "GET", r.Method)
}
}
Table Driven Testing
This is an example to test request headers in a Table Driven Testing manner.