httptest 的介绍与使用

栏目: 编程工具 · 发布时间: 6年前

内容简介:在写完接口之后都需要对接口进行测试,在 golang 标准库中提供因为接口都是需要 IP 地址或域名来访问,

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

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

const DefaultRemoteAddr = "1.2.3.4"

重要的方法

NewRequest(请求体)

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

方法定义:

func NewRequest(method, target string, body io.Reader) *http.Request
method
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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Google's PageRank and Beyond

Google's PageRank and Beyond

Amy N. Langville、Carl D. Meyer / Princeton University Press / 2006-7-23 / USD 57.50

Why doesn't your home page appear on the first page of search results, even when you query your own name? How do other web pages always appear at the top? What creates these powerful rankings? And how......一起来看看 《Google's PageRank and Beyond》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具