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`)
      })
   })
}
复制代码
相关推荐
ArixBit9 分钟前
从目录分层到交付验证:我的 Go 后端工程实践
go
卷无止境10 分钟前
Apache Ossie:打破数据孤岛的语义互操作标准
后端·数据分析
晓杰在写后端14 分钟前
从0到1实现Balatro游戏后端(11):商店商品池与运行时商品实例生成
后端·游戏开发
AskHarries1 小时前
OAuth 登录怎么接
后端
掘金者阿豪2 小时前
上线前能跑,上线后挂了,三个隐性的SQL陷阱
后端
用户8356290780512 小时前
如何使用 Python 为 PDF 添加和管理图层
后端·python
SimonKing2 小时前
那个号称"对标 Spring"的国产框架 Solon,到底行不行?
java·后端·程序员
霸道流氓气质2 小时前
SpringBoot中使用字典驱动的动态路由示例
java·spring boot·后端
用户69371750013843 小时前
Kimi K3 综合能力处于全球第一梯队
android·前端·后端
anno3 小时前
Agent 新手 Skill 优先级指南:从第一套必装工作流,到专业能力补全
前端·后端