Love HTTP Tests with tf

Elliot Chance

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.

Elliot Chance

Written by

I’m a data nerd and TDD enthusiast from Sydney. I love exploring new technologies and working on modern ways to solve age old problems 🤓 elliotchance@gmail.com

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade