/note/tech

ginのリクエストハンドラをユニットテスト

こんな感じ↓でgin.CreateTestContextでコンテキストを作る&ルーティングを定義して実行してやればOKぽい

package example

import (
    "net/http"
    "net/http/httptest"
    "testing"

    "github.com/gin-gonic/gin"
)

func TestGetRoot(t *testing.T) {

    gin.SetMode(gin.TestMode)

    w := httptest.NewRecorder()
    _, r := gin.CreateTestContext(w)

    r.GET("/", HuddlerFunction)

    req, _ := http.NewRequest("GET", "/", nil)
    r.ServeHTTP(w, req)

    asserts := assert.New(t)
    asserts.Equal(w.Code, 200)
}