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`)
      })
   })
}
复制代码
相关推荐
AlexDeng20 分钟前
EF Core 开发实践:Left Join 查询的多种实现方式
后端
马卡巴卡27 分钟前
用Spring的ApplicationEventPublisher进行事件发布和监听
后端
y***n61434 分钟前
springboot项目架构
spring boot·后端·架构
无名之辈J41 分钟前
生产环境慢 SQL 排查与优化
后端
悟能不能悟1 小时前
jasper里面$F和$P的区别
开发语言·后端
短剑重铸之日1 小时前
《7天学会Redis》Day 3 - 持久化机制深度解析
java·redis·后端·缓存
萧曵 丶1 小时前
Spring 全套高频面试题(由浅到深 完整版)
java·后端·spring
武子康1 小时前
大数据-213 Python 手写 K-Means 聚类实战(鸢尾花 Iris 数据集):从距离函数到迭代收敛与坑点
大数据·后端·机器学习
神奇小汤圆1 小时前
MySQL大事务的Recovery优化
后端
魔术师卡颂1 小时前
提问量暴跌 80% ,Stack Overflow 却赚翻了?
前端·后端·ai编程