Search code examples
gogo-gin

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


I'm writing tests for a Gin-Gonic based service. I have a handler which does not accept the gin context as a parameter. Example:

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

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

I want to write the test for this method but I dont know how I should be passing it the mock Gin Context.

If I was doing this for any other method (like the Ping method below) which accepts the Gin Context as an argument, this is how I would be doing it.

func (*handler) Ping(c *gin.Context) {
    c.String(http.StatusOK, "Pong")
    c.Writer.WriteHeaderNow()
} // Method

In the test:

handler := NewHandler()
recorder := httptest.NewRecorder()
mockGinContext, _ := gin.CreateTestContext(recorder)
handler.Ping(mockGinContext)

For Handler1, how should I pass it the TestContext?


Solution

  • You should use same strategy in test:

    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)