What's the best way for testing Gin routes in Go?
from lena@gregtech.eu to programming@programming.dev on 26 Jul 16:00
https://gregtech.eu/post/16417851

cross-posted from: gregtech.eu/post/16416819

Hi, what’s the best way for testing a gin route?

I currently have one function where the routes are defined. Here it is:

package router

import (
	"github.com/gin-gonic/gin"
	"github.com/gragorther/epigo/handlers"
	"github.com/gragorther/epigo/middlewares"
)

func Setup(userUserStore handlers.UserUserStore, groupGroupStore handlers.GroupGroupStore, groupAuthStore handlers.GroupAuthStore, messageAuthStore handlers.MessageAuthStore, messageMessageStore handlers.MessageMessageStore, middlewareUserStore middlewares.UserStore) *gin.Engine {
	r := gin.Default()
	r.Use(middlewares.ErrorHandler())

	userHandler := handlers.NewUserHandler(userUserStore)
	authHandler := middlewares.NewAuthMiddleware(middlewareUserStore)
	groupHandler := handlers.NewGroupHandler(groupGroupStore, groupAuthStore)
	messageHandler := handlers.NewMessageHandler(messageMessageStore, messageAuthStore)

	// user stuff
	r.POST("/user/register", userHandler.RegisterUser)
	r.POST("/user/login", userHandler.LoginUser)
	r.GET("/user/profile", authHandler.CheckAuth, userHandler.GetUserProfile)
	r.PUT("/user/setEmailInterval", authHandler.CheckAuth, userHandler.SetEmailInterval)

	// groups
	r.DELETE("/user/groups/delete/:id", authHandler.CheckAuth, groupHandler.DeleteGroup)
	r.POST("/user/groups/add", authHandler.CheckAuth, groupHandler.AddGroup)
	r.GET("/user/groups", authHandler.CheckAuth, groupHandler.ListGroups) // list groups
	r.PATCH("/user/groups/edit/:id", authHandler.CheckAuth, groupHandler.EditGroup)

	// lastMessages
	r.POST("/user/lastMessages/add", authHandler.CheckAuth, messageHandler.AddLastMessage)
	r.GET("/user/lastMessages", authHandler.CheckAuth, messageHandler.ListLastMessages)
	r.PATCH("/user/lastMessages/edit/:id", authHandler.CheckAuth, messageHandler.EditLastMessage)
	r.DELETE("/user/lastMessages/delete/:id", authHandler.CheckAuth, messageHandler.DeleteLastMessage)
	return r
}

so, my question is, how can I test just one route? should I run this function in every test and send a request to a route with httptest? Or should I set up my handlers like it’s described at gin-gonic.com/en/docs/testing/

(like this)

func postUser(router *gin.Engine) *gin.Engine {
  router.POST("/user/add", func(c *gin.Context) {
    var user User
    c.BindJSON(&user)
    c.JSON(200, user)
  })
  return router
}

let me know if you have any other questions about my code.

It’s available on github: github.com/gragorther/epigo

#programming

threaded - newest