Go HTTP handler is limited when it comes to handling/testing URL parameters so this test demonstrates how you can test such endpoints. It also has a test that doesn't require URL parameters.


Endpoint without parameter


package league

import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/assert"
)

func TestCreate_Handle(t *testing.T) {
requestBody := `
{
"name": "League 1",
"international_rank": 1,
"address": "Address 1",
"is_active": true,
"founded_at": "1900-01-02"
}
`

responseBody := `
{
"data": {
"id": ID_REGEX
}
}
`

rq := httptest.NewRequest(http.MethodPost, "/leagues", strings.NewReader(requestBody))
rw := httptest.NewRecorder()

yourHandler.Handle(rw, rq)

// Flatten formatted json string.
buffer := new(bytes.Buffer)
_ = json.Compact(buffer, []byte(responseBody))

// Replace placeholders with corresponding regex patterns.
expectedBody := strings.ReplaceAll(buffer.String(), "ID_REGEX", "\\d+/g") // Or "\\w+" for strings, or just use ".*?" to match anything

assert.Regexp(t, expectedBody, rw.Body.String())
assert.Equal(t, http.StatusCreated, rw.Code)
}

Endpoint with parameter


package league

import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/httptest"
"testing"
"github.com/julienschmidt/httprouter"
"github.com/stretchr/testify/assert"
)

func TestRetrieve_Handle(t *testing.T) {
responseBody := `
{
"data": {
"id": 1,
"name": "La Liga",
"international_rank": 1,
"address": "Spain",
"is_active": true,
"founded_at": "1929-01-01",
"created_at": "2019-12-31 23:59:59",
"deleted_at": ""
}
}
`

rtr := httprouter.New()
rtr.HandlerFunc(http.MethodGet, "/leagues/:id", yourHandler.Handle)

srv := httptest.NewServer(rtr)
defer srv.Close()

req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/leagues/%s", srv.URL, 123), nil)
if err != nil {
t.Error(err)
}

res, err := http.DefaultClient.Do(req)
if err != nil {
t.Error(err)
}
defer res.Body.Close()

body, err := ioutil.ReadAll(res.Body)
if err != nil {
log.Fatal(err)
}

// Flatten formatted json string.
buffer := new(bytes.Buffer)
_ = json.Compact(buffer, []byte(responseBody))

assert.Equal(t, buffer.String(), string(body))
assert.Equal(t, http.StatusOK, res.StatusCode)
}