
如何使用请求数据绑定对 Go Gin 处理程序函数进行单元测试
在单元测试 Gin 处理程序函数中,正确初始化和设置请求正文和查询参数至关重要。让我们深入研究如何有效地测试 c.BindQuery。
在提供的测试代码中,c.BindQuery 不起作用,因为 HTTP 请求未使用任何查询参数进行初始化。要模拟 c.BindQuery,您需要创建一个测试请求并相应地设置其 URL 和 URL.RawQuery。这是一个改进的版本:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | func mockGin() (*gin.Context, *httptest.ResponseRecorder) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
req := &http.Request{
URL: &url.URL{},
Header: make(http.Header),
}
testQuery := weldprogs.QueryParam{ }
q := req.URL.Query()
for _, s := range testQuery.Basematgroup_id {
q.Add( "basematgroup_id" , s)
}
req.URL.RawQuery = q.Encode()
c.Request = req
return c, w
}
|
登录后复制
模拟查询绑定后,您可以在处理函数 GetMaterialByFilter 中测试 c.BindQuery。
测试服务依赖关系
您的处理函数也会调用该服务services.WeldprogService.GetMaterialByFilter。要使此调用可测试,该服务应该是一个可以作为处理程序的依赖项注入的接口。
以下是执行此操作的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | type WeldprogService interface {
GetMaterialByFilter(query *weldprogs.QueryParam) ([]weldprogs.Material, error)
}
func GetMaterialByFilter(c *gin.Context) {
weldprogService := mustGetService(c)
materialByFilter, getErr := weldprogService.GetMaterialByFilter(&queryParam)
}
func mustGetService(c *gin.Context) WeldprogService {
svc, exists := c.Get( "svc_context_key" )
if !exists {
panic( "service was not set" )
}
return svc.(WeldprogService)
}
|
登录后复制
现在,您可以模拟单元测试中的服务并控制其行为:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | type mockSvc struct {
}
func TestGetMaterialByFilter(t *testing.T) {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set( "svc_context_key" , &mockSvc{})
GetMaterialByFilter(c)
}
|
登录后复制
以上是如何使用数据绑定和服务依赖性有效地对 Go Gin 处理程序功能进行单元测试?的详细内容。更多信息请关注PHP中文网其他相关文章!