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`)
      })
   })
}
复制代码
相关推荐
脚本自动化开发5 小时前
折叠双屏MU156LA:写稿修图游戏体验
后端
脚本自动化开发5 小时前
AI短剧800集讲规矩,观众忘了是AI
后端
Csvn7 小时前
安装、升级与目录结构
后端·nginx
皮皮林5518 小时前
万能通用!权限系统就该这么设计
后端
Warson_L8 小时前
高性能架构设计
python·go
GoAI9 小时前
DeepSeek Harness Memory (一)主流记忆插件总结
后端·算法·面试
我不会起名字3229 小时前
Redis 从 0 到 1(三十七·收官):36 篇浓缩成 1 张知识地图 + 50 项生产 Checklist
redis·go·知识体系·checklist·收官
橙子家10 小时前
RESTful 接口:它并非标准或协议,而是一种【架构风格】
后端
Mz码不住10 小时前
用 Wails 写一个跨平台进程管理器
go
小兔子10 小时前
dict.get 的默认值每次都会求值,哪怕键本来就在
后端