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`)
      })
   })
}
复制代码
相关推荐
lzzy_lx_208919 分钟前
Spring Boot登录认证实现学习心得:从皮肤信息系统项目中学到的经验
java·spring boot·后端
前端付豪36 分钟前
21、用 Python + Pillow 实现「朋友圈海报图生成器」📸(图文合成 + 多模板 + 自动换行)
后端·python
MaxHua1 小时前
以 AI 之力重塑 Java 研发,解锁高效开发新范式
后端
Determined_man1 小时前
多了这个@ResponseBody和没加有什么区别?
后端
八苦1 小时前
VKProxy新增一些功能
后端
ApeAssistant1 小时前
Log4j2.xml配置总结,就这个标题就挺好
后端·apache log4j
WanderInk2 小时前
揭秘Java协变返回类型:让你的API少一点强转,多一点优雅
java·后端
心在飞扬2 小时前
AI开发应用 01-nodejs快速入门
后端·aigc·dnodejs
Ray662 小时前
「阅读笔记」elasticSearch 是什么?工作原理是怎么样的?
后端