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`)
      })
   })
}
复制代码
相关推荐
颜酱6 小时前
DFS 岛屿系列题全解析
javascript·后端·算法
小码哥_常7 小时前
Java后端定时任务抉择:@Scheduled、Quartz、XXL - Job终极对决
后端
uzong7 小时前
Skill 被广泛应用,到底什么是 Skill,今天详细介绍一下
人工智能·后端·面试
小码哥_常7 小时前
Kafka平替!SpringBoot+Redis Stream+消费组打造极致消息队列
后端
IT_陈寒9 小时前
Redis缓存击穿:3个鲜为人知的防御策略,90%开发者都忽略了!
前端·人工智能·后端
uzong9 小时前
Harness Engineering 是什么?一场新的 AI 范式已经开始
人工智能·后端·架构
唐叔在学习10 小时前
Python桌面端应用最小化托盘开发实践
后端·python·程序员
yuhaiqiang10 小时前
被 AI 忽悠后,开始怀念搜索引擎了?
前端·后端·面试
二闹11 小时前
Python文件读取三巨头你该选择哪一个?
后端·python
苏三说技术11 小时前
推荐几个牛逼的AI Agent项目
后端