Skip to content

Memo: Write Tests

Wenxuan edited this page Feb 10, 2022 · 1 revision

Unit test a gin handler

To test a gin handler like:

func HandleRequest(c *gin.Context) {
	...
}

You can use gintest.CtxGet to simulate a GET request performed over this context:

c, r := gintest.CtxGet(nil)
// Or pass query params:
// c, r := gintest.CtxGet(url.Values{"query_param_foo": []string{"value"}})
HandleRequest(c)
require.Len(t, c.Errors, 0)
require.Equal(t, http.StatusOK, r.Code)
require.Equal(t, "...", r.Body.String())

Use gintest.CtxPost to simulate a POST request with specified request body:

c, r = gintest.CtxPost(nil, `{"foo":"bar"}`)

Integration test a gin handler with middlewares or routers

To test the behavior when a gin handler is integrated with the others, you can use the standard httptest:

engine := gin.New()
engine.Use(gin.Recovery())
// Add other middlewares that you want to test together with
engine.GET("/test", func(c *gin.Context) {
	...
})

r := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/test", nil)
engine.ServeHTTP(r, req)
require.Equal(http.StatusOK, r.Code)
require.Equal("...", r.Body.String())