1 回答
TA贡献1842条经验 获得超22个赞
要测试涉及 HTTP 请求的操作,您必须实际初始化 a 并将其设置为 Gin 上下文。要专门测试,正确初始化请求和:*http.Requestc.BindQueryURLURL.RawQuery
func mockGin() (*gin.Context, *httptest.ResponseRecorder) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
// test request, must instantiate a request first
req := &http.Request{
URL: &url.URL{},
Header: make(http.Header), // if you need to test headers
}
// example: req.Header.Add("Accept", "application/json")
// request query
testQuery := weldprogs.QueryParam{/* init fields */}
q := req.URL.Query()
for _, s := range testQuery.Basematgroup_id {
q.Add("basematgroup_id", s)
}
// ... repeat for other fields as needed
// must set this, since under the hood c.BindQuery calls
// `req.URL.Query()`, which calls `ParseQuery(u.RawQuery)`
req.URL.RawQuery = q.Encode()
// finally set the request to the gin context
c.Request = req
return c, w
}
如果需要模拟 JSON 绑定,请参阅此答案。
无法按原样测试服务调用。要具有可测试性,它必须(理想情况下)是一个接口,并以某种方式注入作为处理程序的依赖项。services.WeldprogService.GetMaterialByFilter(&queryParam)
假设它已经是一个接口,要使其可注入,您要么需要它作为处理程序参数 - 但这迫使您更改处理程序的签名 - 或者将其设置为Gin上下文值:
func GetMaterialByFilter(c *gin.Context) {
//...
weldprogService := mustGetService(c)
materialByFilter, getErr := weldprogService.GetMaterialByFilter(&queryParam)
// ...
}
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)
}
然后,您可以在单元测试中模拟它:
type mockSvc struct {
}
// have 'mockSvc' implement the interface
func TestGetMaterialByFilter(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
// now you can set mockSvc into the test context
c.Set("svc_context_key", &mockSvc{})
GetMaterialByFilter(c)
// ...
}
- 1 回答
- 0 关注
- 144 浏览
添加回答
举报
