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

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

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)

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:

确定