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`)
      })
   })
}
复制代码
相关推荐
weixin_4569042711 小时前
Spring Boot 用户管理系统
java·spring boot·后端
cyforkk12 小时前
Spring 异常处理器:从混乱到有序,优雅处理所有异常
java·后端·spring·mvc
程序员爱钓鱼13 小时前
Go语言实战案例-开发一个Markdown转HTML工具
前端·后端·go
桦说编程13 小时前
爆赞!完全认同!《软件设计的哲学》这本书深得我心
后端
thinktik13 小时前
还在手把手教AI写代码么? 让你的AWS Kiro AI IDE直接读飞书需求文档给你打工吧!
后端·serverless·aws
老青蛙16 小时前
权限系统设计-用户设计
后端
echoyu.16 小时前
消息队列-初识kafka
java·分布式·后端·spring cloud·中间件·架构·kafka
yuluo_YX16 小时前
Go Style 代码风格规范
开发语言·后端·golang
David爱编程16 小时前
从 JVM 到内核:synchronized 与操作系统互斥量的深度联系
java·后端