httptest 的介绍与使用

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

内容简介:在写完接口之后都需要对接口进行测试,在 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


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

查看所有标签

猜你喜欢:

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

驯服烂代码

驯服烂代码

伍斌 / 机械工业出版社 / 2014-11 / 69.00

Kent Beck、Martin Fowler、Michael C. Feathers、Robert C. Martin、Joshua Kerievsky、Gerard Meszaros等大师们的传世著作为如何提升编程技艺和代码质量提供了思想和原则上的指导,本书则为实践和融合这些思想、原则提供了过程和方法上指导。本书通过编程操练的方式讲述了如何用TDD(测试驱动开发)的方法来驯服烂代码,通过结对编......一起来看看 《驯服烂代码》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

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

RGB CMYK 互转工具