如何将 TestContext 传递给不接受 Gin 上下文作为参数的方法?

How to pass TestContext to a method which does not accept the Gin Context as an argument?

我正在为基于 Gin-Gonic 的服务编写测试。 我有一个不接受 gin 上下文作为参数的处理程序。 示例:

func (h *handler) Handler1(isTrue bool) func(*gin.Context) {

    return func(c *gin.Context) { .. Do Something }
}

我想为此方法编写测试,但我不知道如何将模拟 Gin 上下文传递给它。

如果我对接受 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传递给它?

你应该在测试中使用相同的策略:

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)