github.com/elliotchance/tf now supports super easy HTTP testing by using the ServeHTTP function.

This means that you do not have to run the server and it’s compatible with all HTTP libraries and frameworks but has all the functionality of the server itself.

The simplest example is to use the default muxer in the http package:

http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, World!")
})

And now we can write some tests:

func TestHTTPRouter(t *testing.T) {
run := tf.ServeHTTP(t, http.DefaultServeMux.ServeHTTP)
run(&tf.HTTPTest{
Path: "/hello",
Status: http.StatusOK,
ResponseBody: strings.NewReader("Hello, World!"),
})
run(&tf.HTTPTest{
Path: "/world",
Status: http.StatusNotFound,
})
}

It is compatible with all HTTP frameworks because they must all expose a ServeHTTPwhich is the entry point for the request router/handler.

There are many more options for HTTPTest.

Some HTTP tests require multiple operations (such as CRUD operations), you can use MultiHTTPTest for this:

run(&tf.MultiHTTPTest{
Steps: []*tf.HTTPTest{
{
Path: "/save",
Method: http.MethodPut,
RequestBody: strings.NewReader(`{"foo":"bar"}`),
Status: http.StatusCreated,
},
{
Path: "/fetch",
Method: http.MethodGet,
Status: http.StatusOK,
ResponseBody: strings.NewReader(`{"foo":"bar"}`),
},
},
})

Each step will only proceed if the previous step was successful.

Originally published at http://elliot.land on September 12, 2018.

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓 elliotchance@gmail.com

I’m a data nerd and TDD enthusiast originally from Sydney. Currently working for Uber in New York. My thoughts here are my own. 🤓 elliotchance@gmail.com