gin 静态测试,创建gin.Context对象

在用convey包进行单元测试的时候,遇到某些被测函数的入参是:ctx *gin.Context。

git 复制代码
github.com/smartystreets/goconvey/convey

此时可以按照下面的方法new一个测试context即可,前面的new request需要带着哈。

go 复制代码
func TestAssembleStock(t *testing.T) {
   r := &articleService{}         // Create an instance of the articleService // Sample dataJson
   request := vo.ArticleRequest{} // Create a sample ArticleRequest
   request.Version = "6.0.0"// 创建一个新的 Gin 引擎
   // 创建一个模拟的 HTTP 请求
   req, err := http.NewRequest("GET", "/your/route", nil)
   if err != nil {
      t.Fatal(err)
   }
   // 使用 gin 的上下文构造函数创建一个上下文对象
   ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
   ctx.Request = req

   Convey("Given a list of stocks", t, func() {
      jsonData := []byte(`{"result":{"data":[{"stocks":[{"code":["hk02331","02331"],"market":"hk","other_codes":[{"code":["usLNNGY","LNNGY"],"market":"us"},{"code":["hk82331","82331"],"market":"hk"}],"tf":13,"type":"stocks","weight":0.255,"word":"李宁"},{"code":["hk00012","00012"],"market":"hk","tf":1,"type":"stocks","weight":0.02,"word":"恒基地产"}]}]}}`)
      Convey("When content is present with content for stocks", func() {
         result, err := r.assembleStock(ctx, request, jsonData)                                                  // Call the checkWord function
         So(err, ShouldBeNil)                                                                                              // Assert that error is nil
         So(string(result), ShouldEqual, `1`)
      })
   })
}
复制代码
相关推荐
小谢小哥几秒前
50-Redis高级应用详解
后端
小谢小哥9 分钟前
51-限流算法详解
java·后端·架构
阿丰资源20 分钟前
基于SpringBoot+MySQL的在线拍卖系统设计与实现(附源码)
spring boot·后端·mysql
在屏幕前出油25 分钟前
08. ORM——快速开始
数据库·后端·python·sql·pycharm·orm
budingxiaomoli25 分钟前
SpringBoot快速上手
java·spring boot·后端
SimonKing44 分钟前
AI编程工具装了一大堆,Skills 管理乱成粥?这个开源神器一招搞定!
java·后端·程序员
IT_陈寒1 小时前
Python中的这个可变默认参数陷阱我居然又踩了
前端·人工智能·后端
卷毛的技术笔记1 小时前
从零到一:深入浅出分布式锁原理与Spring Boot实战(Redis + ZooKeeper)
java·spring boot·redis·分布式·后端·面试·java-zookeeper
念何架构之路1 小时前
图解defer
开发语言·后端·golang
ん贤2 小时前
如何设计一个灵活、高效、安全的 AI 工具系统
人工智能·安全·go