最近在写 <a src="https://github.com/Hexilee/rady"> rady </a> 时候,想集成一个 http 测试库,一搜发现 go 自带一个 httptest
然后给出的例子是这样的
```go
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 和 <a src="https://github.com/stretchr/testify">testify/assert</a> 封装了一下,写了 <a src="https://github.com/Hexilee/htest"> htest</a>
项目
它用起来大概长这样,感受一下
```go
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
```go
// 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
```go
// 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")
}
```
更多功能看 <a src="https://github.com/Hexilee/htest"> htest</a>
有疑问加站长微信联系(非本文作者))