用 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 次點擊  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.