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`)
      })
   })
}
复制代码
相关推荐
ServBay3 分钟前
Grok Bot 还是 OpenClaw?聊聊真正能替人打杂的 AI 智能体
后端·aigc·grok
掘金挖土14 分钟前
前端手摸手跑路之 AI 应用开发(五)
前端·后端
弈栈录26 分钟前
LangGraph 入门:用状态机设计可靠的 Agent 工作流
后端·程序员
LEE2 小时前
前端转型全栈 00:AI 时代该学哪些,不该学哪些
前端·后端
Go_error2 小时前
上下文取消链:摧毁我们支付系统的 bug
后端·go
无限压榨切图仔2 小时前
一个优惠券需求改了三端,我才明白全栈不是多学一门语言
前端·后端
CRZZX2 小时前
阶段 0.1:为 AI Agent 项目建立敏感配置治理与安全基线
后端
用户2181697049302 小时前
go-zero 获取参数 yaml 配置文件 参数校验 validate
go
Zane19942 小时前
用了Optional,为什么NPE还是防不住?
java·后端
yunwei372 小时前
eBPF 示例教程:实现 `scx_nest` 调度器
linux·后端·性能优化