在Golang中用自定义头文件测试一个端点

155 阅读1分钟

如果你想测试一个需要在Golang中定制头文件的端点,你可以使用下面的例子:

package user

import (
	"net/http"
)

type List struct {}

func (l List) Handle(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	w.Header().Set("X-Request-Id", r.Header.Get("X-Request-Id"))

	w.WriteHeader(http.StatusOK)

	_, _ = w.Write([]byte("inanzzz"))
}
package user

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

func TestList_Handle(t *testing.T) {
	req := httptest.NewRequest(http.MethodGet, "/api/v1/users", nil)
	req.Header.Set("X-Request-Id", "Test-Header")
	res := httptest.NewRecorder()

	list := List{}
	list.Handle(res, req)

	result := res.Result()

	body, err := ioutil.ReadAll(result.Body)
	if err != nil {
		t.Error(err)
	}
	result.Body.Close()

	if http.StatusOK != result.StatusCode {
		t.Error("wanted", http.StatusOK, "got", result.StatusCode)
	}
	if "Test-Header" != result.Header.Get("X-Request-Id") {
		t.Error("wanted Test-Header got", result.Header.Get("X-Request-Id"))
	}
	if "inanzzz" != string(body) {
		t.Error("wanted inanzzz got", string(body))
	}
}