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`)
      })
   })
}
复制代码
相关推荐
huzhongqiang4 分钟前
Python全站链接爬取工具优化:支持过滤和断点续爬
后端·爬虫
神奇小汤圆5 分钟前
SpringBoot 4 最被低估的新特性:Spring Data AOT
后端
杨运交6 分钟前
[004][缓存模块]Caffeine缓存自定义:构建灵活的Spring Boot缓存管理器
后端
刀法如飞10 分钟前
一款开箱即用的Flask 3.0 MVC工程脚手架,面向AI开发
后端·python·flask
神奇小汤圆26 分钟前
美团Java一面:布隆过滤器有什么缺点?
后端
Zfox_28 分钟前
【LangChain】核心组件(上)
后端·langchain·ai编程
苏三说技术1 小时前
京东二面:假如SQL中join了10张表,如何优化性能?
后端
dvjr cloi1 小时前
Spring Framework 中文官方文档
java·后端·spring
Ruci ALYS1 小时前
SpringBoot Maven快速上手
spring boot·后端·maven