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`)
      })
   })
}
复制代码
相关推荐
冷崖4 分钟前
原子锁操作
c++·后端
moxiaoran57536 分钟前
Spring AOP开发的使用场景
java·后端·spring
一线大码4 小时前
Gradle 基础篇之基础知识的介绍和使用
后端·gradle
Java猿_4 小时前
Spring Boot 集成 Sa-Token 实现登录认证与 RBAC 权限控制(实战)
android·spring boot·后端
小王师傅665 小时前
【轻松入门SpringBoot】actuator健康检查(上)
java·spring boot·后端
码事漫谈5 小时前
C++高并发编程核心技能解析
后端
码事漫谈5 小时前
C++与浏览器交织-从Chrome插件到WebAssembly,开启性能之门
后端
源代码•宸6 小时前
goframe框架签到系统项目(BITFIELD 命令详解、Redis Key 设计、goframe 框架教程、安装MySQL)
开发语言·数据库·经验分享·redis·后端·mysql·golang
⑩-6 小时前
SpringCloud-Nacos 配置中心实战
后端·spring·spring cloud
java1234_小锋7 小时前
[免费]SpringBoot+Vue勤工助学管理系统【论文+源码+SQL脚本】
spring boot·后端·mybatis·勤工助学