Using testify & httpexpect

While Go's standard library provides excellent tools for testing HTTP handlers, third-party packages like testify and httpexpect can make your tests easier to write.

Testify

The testify package provides enhanced assertion functions that can make the tests more readable and provide better error messages.

Installation

go get github.com/stretchr/testify
go get github.com/gavv/httpexpect/v2

Basic Usage

package main

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/gavv/httpexpect/v2"
	"github.com/stretchr/testify/assert"
)

func TestServer(t *testing.T) {
	// Set up routes and testserver
	mux := http.NewServeMux()
	mux.HandleFunc("GET /json/{word}", handler4)

	server := httptest.NewServer(mux)
	defer server.Close()

	// Create httpexpect instance
	e := httpexpect.Default(t, server.URL)

	var target map[string]string

	e.GET("/json/hello").
		Expect().
		Status(http.StatusOK).
		JSON().Object().Decode(&target)

	assert.Equal(t, "hello", target["word"])
}