Test Go http.Handler

Verify handler by recording the response. Then check status code and some expected values in the resulting body. Create and edit hello_world_test.go.


package main

import (
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"strings"
	"testing"
)

func Test_helloWorld(t *testing.T) {
	w := httptest.NewRecorder()
	r := httptest.NewRequest("GET", "/", http.NoBody)

	helloWorld()(w, r)

	resp := w.Result()
	if got, exp := resp.StatusCode, 200; got != exp {
		t.Error(r.Method, r.URL, got, ", expect", exp)
	}

	data, _ := ioutil.ReadAll(resp.Body)
	body := string(data)
	if exp := "Hello world"; !strings.Contains(body, exp) {
		t.Error(body, "\nbody is missing ", exp)
	}
}

References: http/httptest, testing and helloWorld

Compile and test your code

$ go test -v .