在Golang中对有和无URL参数的端点进行单元测试

110 阅读1分钟

Go HTTP处理程序在处理/测试URL参数时是有限的,所以这个测试演示了如何测试这种端点。它也有一个不需要URL参数的测试。

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)
}
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)
}