51Testing软件测试论坛

 找回密码
 (注-册)加入51Testing

QQ登录

只需一步,快速开始

微信登录,快人一步

查看: 1315|回复: 0
打印 上一主题 下一主题

[转贴] go 基于gin的单元测试

[复制链接]
  • TA的每日心情
    无聊
    2024-3-7 09:16
  • 签到天数: 43 天

    连续签到: 2 天

    [LV.5]测试团长

    跳转到指定楼层
    1#
    发表于 2021-11-24 16:08:39 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
    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





    分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    本版积分规则

    关闭

    站长推荐上一条 /1 下一条

    小黑屋|手机版|Archiver|51Testing软件测试网 ( 沪ICP备05003035号 关于我们

    GMT+8, 2024-5-2 15:57 , Processed in 0.060114 second(s), 23 queries .

    Powered by Discuz! X3.2

    © 2001-2024 Comsenz Inc.

    快速回复 返回顶部 返回列表