如何测试使用中间件的处理程序?

huangapple go评论105阅读模式
英文:

How to test handler which uses middleware

问题

如何测试使用中间件的处理程序
我正在尝试为使用中间件但不作为依赖项的处理程序编写单元测试。

我的处理程序代码如下:

  1. package handlers
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/google/uuid"
  5. )
  6. type Handler interface{
  7. FindById(c *gin.Context)
  8. }
  9. type handler struct{}
  10. func (*handler) FindById(context *gin.Context) {
  11. id := context.MustGet("id").(uuid.UUID)
  12. // 使用`id`做一些操作...
  13. }

中间件的代码如下:

  1. package middlewares
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. "github.com/google/uuid"
  6. )
  7. func Id(context *gin.Context) {
  8. id, err := uuid.Parse(context.Param("id"))
  9. if err != nil {
  10. context.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
  11. "errors": []string{"id is not valid UUID"},
  12. })
  13. return
  14. }
  15. context.Set("id", id)
  16. }

如何模拟:
id := context.MustGet("id").(uuid.UUID)
以测试handler结构体?

英文:

How to test handler which uses middleware

I'm trying to make unit test for handler which uses middleware but not as a dependency.

My code for handler looks like this:

  1. package handlers
  2. import (
  3. "github.com/gin-gonic/gin"
  4. "github.com/google/uuid"
  5. )
  6. type Handler interface{
  7. FindById(c *gin.Context)
  8. }
  9. type handler struct{}
  10. func (*handler) FindById(context *gin.Context) {
  11. id := context.MustGet("id").(uuid.UUID)
  12. // do something with `id`...
  13. }

And the code for middleware:

  1. package middlewares
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. "github.com/google/uuid"
  6. )
  7. func Id(context *gin.Context) {
  8. id, err := uuid.Parse(context.Param("id"))
  9. if err != nil {
  10. context.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
  11. "errors": []string{"id is not valid UUID"}
  12. })
  13. return
  14. }
  15. context.Set("id", id)
  16. }

How can I mock:

id := context.MustGet("id").(uuid.UUID)

to test handler struct?

答案1

得分: 1

在上下文中设置键:c.Set("id", uuid)

英文:

Set the key on the context: c.Set("id", uuid)

huangapple
  • 本文由 发表于 2022年2月20日 00:32:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/71186906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定