英文:
How to test handler which uses middleware
问题
如何测试使用中间件的处理程序
我正在尝试为使用中间件但不作为依赖项的处理程序编写单元测试。
我的处理程序代码如下:
package handlers
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type Handler interface{
FindById(c *gin.Context)
}
type handler struct{}
func (*handler) FindById(context *gin.Context) {
id := context.MustGet("id").(uuid.UUID)
// 使用`id`做一些操作...
}
中间件的代码如下:
package middlewares
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func Id(context *gin.Context) {
id, err := uuid.Parse(context.Param("id"))
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"errors": []string{"id is not valid UUID"},
})
return
}
context.Set("id", id)
}
如何模拟:
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:
package handlers
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
type Handler interface{
FindById(c *gin.Context)
}
type handler struct{}
func (*handler) FindById(context *gin.Context) {
id := context.MustGet("id").(uuid.UUID)
// do something with `id`...
}
And the code for middleware:
package middlewares
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
func Id(context *gin.Context) {
id, err := uuid.Parse(context.Param("id"))
if err != nil {
context.AbortWithStatusJSON(http.StatusBadRequest, gin.H{
"errors": []string{"id is not valid UUID"}
})
return
}
context.Set("id", id)
}
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论