美文网首页
go 基于gin的单元测试

go 基于gin的单元测试

作者: bug去无踪 | 来源:发表于2020-01-16 09:55 被阅读0次

    1.方法一:本地启动服务,用浏览器或者postman测试,但是项目有改动再次测试不是很方便
    2.方法二:使用httptest结合testing来实现针对handlers接口函数的单元测试 这里直接使用一个开源的单元测试包,已经封装好了
    github项目地址:https://github.com/Valiben/gin_unit_test

    要测试接口的处理函数
    type User struct {
    Username string form:"username" json:"username" binding:"required"
    Password string form:"password" json:"password" binding:"required"
    Age int form:"age" json:"age" binding:"required"
    }

    func LoginHandler(c *gin.Context) {
    req := &User{}
    if err := c.Bind(req); err != nil {
    log.Printf("err:%v", err)
    c.JSON(http.StatusOK, gin.H{
    "errno": "1",
    "errmsg": "parameters not match",
    })
    return
    }

    // judge the password and username
    if req.UserName != "Valiben" || req.Password != "123456" {
    c.JSON(http.StatusOK, gin.H{
    "errno": "2",
    "errmsg": "password or username is wrong",
    })
    return
    }

    c.JSON(http.StatusOK, gin.H{
    "errno": "0",
    "errmsg": "login success",
    })
    }

    单元测试:

    func init() {
    //初始化路由
    router := gin.New()
    router.POST("/login", LoginHandler)
    myLog := log.New(os.Stdout, "", log.Lshortfile|log.Ltime)
    utilTest.SetRouter(router)
    utilTest.SetLog(myLog)

    }

    type OrdinaryResponse struct {
    Errno string json:"errno"
    Errmsg string json:"errmsg"
    Data UserActivityRespone json:"data"
    }

    func TestLoginHandler(t *testing.T) {
    resp := OrdinaryResponse{}

    err := utils.TestHandlerUnMarshalResp(utils.POST, "/login", utils.Form, user, &resp)
    if err != nil {
    t.Errorf("TestLoginHandler: %v\n", err)
    return
    }

    if resp.Errno != "0" {
    t.Errorf("TestLoginHandler: response is not expected\n")
    return
    }
    t.Log(resp.Data)
    }

    文件上传测试:
    func TestSaveFileHandler(t *testing.T) {
    param := make(map[string]interface{})
    param["file_name"] = "test1.txt"
    param["upload_name"] = "Valiben"

    resp := OrdinaryResponse{}
    err := utils.TestFileHandlerUnMarshalResp(utils.POST, "/upload", (param["file_name"]).(string),
    "file", param, &resp)
    if err != nil {
    t.Errorf("TestSaveFileHandler: %v\n", err)
    return
    }

    if resp.Errno != "0" {
    t.Errorf("TestSaveFileHandler: response is not expected\n")
    return
    }
    }

    转自:https://blog.csdn.net/weixin_34236497/article/details/92386605
    go原生接口单元测试:https://www.jianshu.com/p/1a0ce8ce062a

    相关文章

      网友评论

          本文标题:go 基于gin的单元测试

          本文链接:https://www.haomeiwen.com/subject/nyffzctx.html