Skip to content

Instantly share code, notes, and snippets.

@nidhi-canopas
Last active July 19, 2022 10:02
Show Gist options
  • Select an option

  • Save nidhi-canopas/000b265b154a1aa77b144ad767b84e7e to your computer and use it in GitHub Desktop.

Select an option

Save nidhi-canopas/000b265b154a1aa77b144ad767b84e7e to your computer and use it in GitHub Desktop.
// code
func GetUserId(c *gin.Context) {
fmt.Println(c.Query("foo")) //will print "bar" while running test
fmt.Println(c.Param("id")) // will print "1" while running test
id, _ := strconv.Atoi(c.Param("id"))
c.JSON(http.StatusOK, id)
}
// test
func TestGetUserId(t *testing.T) {
w := httptest.NewRecorder()
ctx := GetTestGinContext(w)
//configure path params
params := []gin.Param{
{
Key: "id",
Value: "1",
},
}
// configure query params
u := url.Values{}
u.Add("foo", "bar")
MockJsonGet(ctx, params, u)
GetUserId(ctx)
assert.EqualValues(t, http.StatusOK, w.Code)
got, _ := strconv.Atoi(w.Body.String())
assert.Equal(t, 1, got)
}
//mock gin context
func GetTestGinContext(w *httptest.ResponseRecorder) *gin.Context {
gin.SetMode(gin.TestMode)
ctx, _ := gin.CreateTestContext(w)
ctx.Request = &http.Request{
Header: make(http.Header),
URL: &url.URL{},
}
return ctx
}
//mock getrequest
func MockJsonGet(c *gin.Context, params gin.Params, u url.Values) {
c.Request.Method = "GET"
c.Request.Header.Set("Content-Type", "application/json")
c.Set("user_id", 1)
// set path params
c.Params = params
// set query params
c.Request.URL.RawQuery = u.Encode()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment