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`)
      })
   })
}
复制代码
相关推荐
星空彼岸0072 小时前
SA-Token在SpringBoot中的实战指南
java·spring boot·后端
树獭叔叔2 小时前
大模型行为塑造:SFT 与 LoRA 深度解析
后端·aigc·openai
Ivanqhz2 小时前
半格与数据流分析的五个要素(D、V、F、I、Λ)
开发语言·c++·后端·算法·rust
盛夏绽放5 小时前
流式响应 线上请求出现“待处理”问题
前端·后端·nginx·proxy
茶杯梦轩5 小时前
从零起步学习并发编程 || 第一章:初步认识进程与线程
java·服务器·后端
ArcX5 小时前
手把手从 0 诠释大模型 API 的本质: Tools + MCP + Skills
前端·后端·ai编程
UrbanJazzerati6 小时前
Python 面向对象编程:抽象类、接口与继承系统教程
后端·面试
李老师的Java笔记6 小时前
深度解析 | SpringBoot源码解析系列(五):@ConfigurationProperties | 配置绑定核心原理+实战避坑
java·spring boot·后端
老骥伏枥~7 小时前
基于Spring Boot + Vue.js的图书管理系统
vue.js·spring boot·后端
Tong Z7 小时前
Spring Boot 请求处理链路
java·spring boot·后端