Home >Backend Development >Golang >How to Effectively Unit Test Gin Handler Functions with Query Parameters?
When unit testing Gin handler functions that bind query parameters, an invalid memory address or nil pointer dereference error occurs due to an improperly initialized HTTP request.
To mock query parameter binding using c.BindQuery(), initialize the HTTP request with the proper URL and URL.RawQuery. Use the following helper function:
func mockGin() (*gin.Context, *httptest.ResponseRecorder) { req := &http.Request{ URL: &url.URL{}, Header: make(http.Header), } q := req.URL.Query() // Add query parameters to the request // ... req.URL.RawQuery = q.Encode() c, _ := gin.CreateTestContext(httptest.NewRecorder()) c.Request = req return c, httptest.NewRecorder() }
To test service calls, make the service an interface and inject it into the handler. You can set the service as a Gin context value, allowing you to mock it in unit tests. For example:
func GetMaterialByFilter(c *gin.Context) { weldprogService := mustGetService(c) // ... Call the service method ... } func mustGetService(c *gin.Context) services.WeldprogService { svc, exists := c.Get("svc_context_key") if !exists { panic("service was not set") } return svc.(services.WeldprogService) }
In the unit test, set a mock service into the context:
c.Set("svc_context_key", &mockSvc{})
where mockSvc implements the service interface.
The above is the detailed content of How to Effectively Unit Test Gin Handler Functions with Query Parameters?. For more information, please follow other related articles on the PHP Chinese website!