我正在為基于 Gin-Gonic 的服務編寫測試。我有一個不接受 gin 上下文作為參數的處理程序。例子:func (h *handler) Handler1(isTrue bool) func(*gin.Context) { return func(c *gin.Context) { .. Do Something }}我想為這個方法編寫測試,但我不知道我應該如何將模擬 Gin Context 傳遞給它。如果我為接受 Gin 上下文作為參數的任何其他方法(如下面的 Ping 方法)執行此操作,我將這樣做。func (*handler) Ping(c *gin.Context) { c.String(http.StatusOK, "Pong") c.Writer.WriteHeaderNow()} // Method在測試中:handler := NewHandler()recorder := httptest.NewRecorder()mockGinContext, _ := gin.CreateTestContext(recorder)handler.Ping(mockGinContext)對于Handler1,我應該如何將它傳遞給 TestContext?
1 回答

楊魅力
TA貢獻1811條經驗 獲得超6個贊
您應該在測試中使用相同的策略:
var h *handler
h = ... // however you create *handler
recorder := httptest.NewRecorder()
mockGinContext, _ := gin.CreateTestContext(recorder)
// note that you will have to know do you want to test both,
// or just one of the handlers returned from Handler1
h.Handler1(true)(mockGinContext)
h.Handler1(false)(mockGinContext)
- 1 回答
- 0 關注
- 143 瀏覽
添加回答
舉報
0/150
提交
取消