用 htest 給 go 寫 http 測試

Hexilee發表於2018-02-27

最近在寫 rady 時候,想整合一個 http 測試庫,一搜發現 go 自帶一個 httptest

然後給出的例子是這樣的

import (
    "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 和 testify/assert 封裝了一下,寫了 htest 專案

它用起來大概長這樣,感受一下

package myapp

import (
    "io"
    "net/http"
)

func NameHandler(w http.ResponseWriter, req *http.Request) {
    io.WriteString(w, `{"name": "hexi"}`)
}
// example/basic_mock_client_test.go
package myapp

import (
    "testing"
    "github.com/Hexilee/htest"
)

func TestNameHandlerFunc(t *testing.T) {
    htest.NewClient(t).
        ToFunc(NameHandler).
        Get("").
        Test().
        StatusOK(). // Assert Status Code
        JSON().
        String("name", "hexi") // Assert response data as JSON
}

也可以測試 http.Handler (http.ServeMux, echo.Echo 等 )

*http.ServeMux

// example/basic_mock_client.go
package myapp

import (
    "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.go
package myapp

import (
    "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

// example/basic_mock_client.go
package myapp

import (
    "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.go
package myapp

import (
    "testing"
    "github.com/Hexilee/htest"
)

func TestNameHandlerEcho(t *testing.T) {
    htest.NewClient(t).
        To(server).
        Get("/name").
        Test().
        StatusOK().
        JSON().
        String("name", "hexi")
}

更多功能看 htest

相關文章