在写完接口之后都需要对接口进行测试,在 golang 标准库中提供 httptest 包来辅助测试。

因为接口都是需要 IP 地址或域名来访问,httptest 包中默认定义了服务地址

const DefaultRemoteAddr = "1.2.3.4"

重要的方法

NewRequest(请求体)

NewRequest 方法用来创建一个 http 的请求体。

方法定义:

func NewRequest(method, target string, body io.Reader) *http.Request
  • method 参数表示测试的接口的 HTTP 方法。
  • target 参数表示接口定义的路由。
  • body 参数表示请求体。

NewRecorder(响应体)

方法定义:

func NewRecorder() *ResponseRecorder

NewRecorder 方法用来创建 http 的响应体。返回的类型是 *httptest.ResponseRecorder ,包含接口返回信息,等价于 http.ResponseWriter

ResponseRecorder类型定义:

type ResponseRecorder struct {        // http 响应码.        Code int        // 头部信息        HeaderMap http.Header        // 返回的 Body        Body *bytes.Buffer        // 是否调用 Flush 方法        Flushed bool}

NewServer(http服务)

方法定义:

func NewServer(handler http.Handler) *Server

NewServer 方法用来创建和启动新的服务。同类的还有 NewTLSServer,用来创建带 SSL 的服务。

type Server struct {        URL      string // 服务地址        Listener net.Listener        // TLS 配置信息        TLS *tls.Config        Config *http.Server}

测试 next/http 库创建的接口

请求接口定义:

func testAPI(w http.ResponseWriter, r *http.Request){}

测试方法定义:

func Test_testApi(t *testing.T) {    tests := []struct {        name string    }{        {            name: "test api",        },    }    for _, tt := range tests {        t.Run(tt.name, func(t *testing.T) {            ts := httptest.NewServer(http.HandlerFunc(testAPI))            defer ts.Close()            params := struct{                "params" string             }{                "params": "paramsBody"            }            paramsByte, _ := json.Marshal(params)            resp, err := http.Post(tserver.URL, "application/json", bytes.NewBuffer(paramsByte))            if err != nil {                t.Error(err)            }            defer resp.Body.Close()            t.Log(resp.StatusCode)            if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusOK {                body, _ := ioutil.ReadAll(resp.Body)                t.Error(string(body))            }        })    }}

测试时通过 httptest.NewServer 创建一个 testAPI 接口的服务。然后通过 http.Post 方法来调用我们创建的服务,达到接口测试时请求的目的。然后判断接口返回的信息是否正确。

测试 Gin 框架的接口

请求接口定义:

func testAPI(ctx *gin.Context){}

测试方法定义:

func Test_testAPI(t *testing.T) {    // 定义路由    router := gin.Default()    router.POST("/test", testAPI)    tests := []struct {        name string    }{        {            name: "test api",        },    }    for _, tt := range tests {        t.Run(tt.name, func(t *testing.T) {            params := struct{                "params" string             }{                "params": "paramsBody"            }            paramsByte, _ := json.Marshal(params)            w := httptest.NewRecorder()            req := httptest.NewRequest("POST", "/test", bytes.NewBuffer(paramsByte))            setup.api.router.ServeHTTP(w, req)            assert.Equal(t, http.StatusOK, w.Code)            result, _ := ioutil.ReadAll(w.Body)            var ret model.MessageResult            if err := json.Unmarshal(result, &ret); err != nil {                t.Error(err)            }            assert.Equal(t, tt.want, ret)        })    }}

测试时需要定义好 gin 的路由,然后创建 httptest.NewRecorder 和 httptest.NewRequest 对象,并调用 gin 路由的 ServeHTTP 方法来执行接口。

ServeHTTP 是 *gin.Engine 实现了 http.Handler 接口。通过这种方式达到请求接口目的。然后判断接口返回的信息是否正确。

小结

接口的测试在开发当中是十分重要,我这里介绍了使用 net/http 和 gin 创建接口的测试用例。

通过 httptest 包能方便的对接口进行单元测试,而不需要单独的起一个服务来进行测试。

Ref

  • https://golang.org/pkg/net/http/httptest/