Home > Back-end >  How to test handler which uses middleware
How to test handler which uses middleware

Time:02-21

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?

CodePudding user response:

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

  • Related