TL; DR
Golang + Ginを使ったリクエストのテスト中でセッションを保存する方法に多少苦戦したので紹介
結論
import (
"net/http/httptest"
"github.com/gin-gonic/gin"
"github.com/gorilla/sessions"
)
func SaveSession(recorder *httptest.ResponseRecorder, context *gin.Context, key string, value interface{}) {
var store = sessions.NewCookieStore([]byte("secret"))
session, _ := store.Get(context.Request, "session")
session.Values[key] = value
session.Save(context.Request, recorder)
}
使い方
import (
"net/http"
"net/http/httptest"
"github.com/gin-gonic/gin"
)
func Router() *gin.Engine {
r := gin.New()
r.GET("/url", func(ctx *gin.Context) {
ctx.Status(http.StatusOK)
})
return r
}
func (suite *Controller) TestIndexSuccess() {
recorder := httptest.NewRecorder()
context, _ := gin.CreateTestContext(recorder)
userID := uint(1)
router := s.Router()
context.Request, _ = http.NewRequest("GET", "/url", nil)
SaveSession(recorder, context, "session key", userID)
router.ServeHTTP(recorder, context.Request)
suite.Equal(http.StatusOK, recorder.Code)
}