如何模擬Gin.Context for BindJSON
測試使用Gin 框架並需要模擬gin.Context for BindJSON 的Go 程式碼時功能,必須確保
w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Request = &http.Request{ Header: make(http.Header), }
func MockJsonPost(c *gin.Context, content interface{}) { c.Request.Method = "POST" c.Request.Header.Set("Content-Type", "application/json") jsonbytes, err := json.Marshal(content) if err != nil { panic(err) } c.Request.Body = io.NopCloser(bytes.NewBuffer(jsonbytes)) }
內容參數可以是任何可編組的資料結構或對應。
範例:
func TestPostImageToDBDao(t *testing.T) { w := httptest.NewRecorder() ctx, _ := gin.CreateTestContext(w) ctx.Request = &http.Request{ Header: make(http.Header), } MockJsonPost(ctx, map[string]interface{}{ "articleUUID": "bea1b24d-0627-4ea0-aa2b-8af4c6c2a41c", "imageNames": "b8119536-fad5-4ffa-ab71-2f96cca19697", }) PostImageToDBDao(ctx) assert.EqualValues(t, http.StatusOK, w.Code) }
相關資源:
以上是如何在 Go 單元測試中有效模擬 gin.Context 的 BindJSON?的詳細內容。更多資訊請關注PHP中文網其他相關文章!