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`)
      })
   })
}
复制代码
相关推荐
ai小鬼头37 分钟前
AIStarter最新版怎么卸载AI项目?一键删除操作指南(附路径设置技巧)
前端·后端·github
Touper.43 分钟前
SpringBoot -- 自动配置原理
java·spring boot·后端
一只叫煤球的猫1 小时前
普通程序员,从开发到管理岗,为什么我越升职越痛苦?
前端·后端·全栈
一只鹿鹿鹿1 小时前
信息化项目验收,软件工程评审和检查表单
大数据·人工智能·后端·智慧城市·软件工程
专注VB编程开发20年2 小时前
开机自动后台运行,在Windows服务中托管ASP.NET Core
windows·后端·asp.net
程序员岳焱2 小时前
Java 与 MySQL 性能优化:MySQL全文检索查询优化实践
后端·mysql·性能优化
一只叫煤球的猫2 小时前
手撕@Transactional!别再问事务为什么失效了!Spring-tx源码全面解析!
后端·spring·面试
旷世奇才李先生3 小时前
Ruby 安装使用教程
开发语言·后端·ruby
沃夫上校6 小时前
Feign调Post接口异常:Incomplete output stream
java·后端·微服务
LeeGe6 小时前
SpringAOP中@within和@annotation以及 @within和@target的区别
后端