用 htest 給 go 寫 http 測試
來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。最近在寫 <a src="https://github.com/Hexilee/rady"> rady </a> 時候,想整合一個 http 測試庫,一搜發現 go 內建一個 httptest然後給出的例子是這樣的```goimport ( "net/http" "net/http/httptest" "testing")func TestHealthCheckHandler(t *testing.T) { handler := func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "<html><body>Hello World!</body></html>") } req := httptest.NewRequest("GET", "http://example.com/foo", nil) w := httptest.NewRecorder() handler(w, req) resp := w.Result() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(resp.StatusCode) fmt.Println(resp.Header.Get("Content-Type")) fmt.Println(string(body)}```emmm,總感覺寫了一些不必要的代碼於是我把 httptest 和 <a src="https://github.com/stretchr/testify">testify/assert</a> 封裝了一下,寫了 <a src="https://github.com/Hexilee/htest"> htest</a> 項目它用起來大概長這樣,感受一下```gopackage myappimport ("io""net/http")func NameHandler(w http.ResponseWriter, req *http.Request) {io.WriteString(w, `{"name": "hexi"}`)}// example/basic_mock_client_test.gopackage myappimport ("testing""github.com/Hexilee/htest")func TestNameHandlerFunc(t *testing.T) {htest.NewClient(t).ToFunc(NameHandler).Get("").Test().StatusOK(). // Assert Status CodeJSON().String("name", "hexi") // Assert response data as JSON}```也可以測試 http.Handler (*http.ServeMux, *echo.Echo 等 )> *http.ServeMux```go// example/basic_mock_client.gopackage myappimport ("io""net/http")var (Mux *http.ServeMux)func init() {Mux = http.NewServeMux()Mux.HandleFunc("/name", NameHandler)}func NameHandler(w http.ResponseWriter, req *http.Request) {io.WriteString(w, `{"name": "hexi"}`)}// example/basic_mock_client_test.gopackage myappimport ("testing""github.com/Hexilee/htest")func TestNameHandler(t *testing.T) {htest.NewClient(t).To(Mux).Get("/name").Test().StatusOK().JSON().String("name", "hexi")}```> *echo.Echo```go// example/basic_mock_client.gopackage myappimport ("io""github.com/labstack/echo")var (server *echo.Echo)func init() {server = echo.New()server.GET("/name", NameHandlerEcho)}func NameHandlerEcho(c echo.Context) error {return c.String(http.StatusOK, `{"name": "hexi"}`)}// example/basic_mock_client_test.gopackage myappimport ("testing""github.com/Hexilee/htest")func TestNameHandlerEcho(t *testing.T) {htest.NewClient(t).To(server).Get("/name").Test().StatusOK().JSON().String("name", "hexi")}```更多功能看 <a src="https://github.com/Hexilee/htest"> htest</a>172 次點擊