go 基于gin的单元测试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了go 基于gin的单元测试相关的知识,希望对你有一定的参考价值。

参考技术A 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框架打造restfull风格API

代码的包结构是在GOPATH环境变量目录中新建了bin src pkg三个目录

如果代码放在了github里 , 那么就在src目录下新建的 github.com/用户名/仓库名  这个目录下进行开发工作

 

 

gin框架现在已经更新到了1.6.0 , 对于后端开发打造restfull 的API接口 ,非常方便使用,Gin 是一个用 Go (Golang) 编写的 HTTP web 框架。 它是一个类似于 martini 但拥有更好性能的 API 框架, 优于 httprouter,速度提高了近 40 倍。

 

引入包的过程  , 如果是使用的go mod和goland的IDE , 那么就非常简单直接在代码中使用 ,IDE和go.mod自动就会把包下载下来

package main
import "github.com/gin-gonic/gin"

func main() {
    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // 监听并在 0.0.0.0:8080 上启动服务
}

如果第一次建项目,还没有go.mod的文件 , 那么在命令行执行go mod tidy ,会把依赖下载下来

 

以上是关于go 基于gin的单元测试的主要内容,如果未能解决你的问题,请参考以下文章

go mod 与单元测试

gin单元测试启动服务后测试controller接口

golang之单元测试

Go的单元测试技巧

4Go语言单元测试性能测试与监控

4Go语言单元测试性能测试与监控