梦幻小丑灯 发表于 2021-11-24 16:08:39

go 基于gin的单元测试

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 {
Errnostring 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(mapinterface{})
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





页: [1]
查看完整版本: go 基于gin的单元测试