Home >Backend Development >Golang >How to Effectively Unit Test Gin Handler Functions with Mocks?
To test operations involving the HTTP request in Gin, initialize an *http.Request and set it to the Gin context. Specifically for testing c.BindQuery, initialize the request's URL and URL.RawQuery:
import ( "net/http/httptest" "github.com/gin-gonic/gin" ) func mockGin() (*gin.Context, *httptest.ResponseRecorder) { w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) // Test request req := &http.Request{ URL: &url.URL{}, Header: make(http.Header), } // Test query testQuery := weldprogs.QueryParam{/* init fields */} q := req.URL.Query() for _, s := range testQuery.Basematgroup_id { q.Add("basematgroup_id", s) } // Set URL.RawQuery req.URL.RawQuery = q.Encode() // Set request to Gin context c.Request = req return c, w }
Refer to this resource for guidance on mocking JSON binding.
Services like services.WeldprogService.GetMaterialByFilter(&queryParam) cannot be tested as is. To make them testable:
Interface and Context Value Approach:
type services interface { GetMaterialByFilter(*weldprogs.QueryParam) (*weldprogs.MaterialByFilter, error) } func mockWeldprogService(service services) { return func(c *gin.Context) { c.Set("svc_context_key", service) } } func TestGetMaterialByFilter(t *testing.T) { w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) c.Use(mockWeldprogService(&mockSvc{})) GetMaterialByFilter(c) // ... }
The above is the detailed content of How to Effectively Unit Test Gin Handler Functions with Mocks?. For more information, please follow other related articles on the PHP Chinese website!