2 回答

TA贡献1772条经验 获得超8个赞
严格来说,你不能以有意义的方式“嘲笑”a,因为它是一个具有未导出的字段和方法。*gin.Contextstruct
此外,不能传递给类型不是 定义为 的函数。处理程序的类型根本不匹配。r.POST()gin.HandlerFuncfunc(*gin.Context)CreateUrl(c Icontext)
如果您的目标是对 Gin 处理程序进行单元测试,则绝对不必模拟 .您应该做的是将测试值设置到其中。为此,您可以简单地使用并手动初始化其中一些字段。更多信息请点击这里。*gin.Contextgin.CreateTestContext()
如果出于其他原因,您的目标是提供在处理程序内部使用的功能的替代实现,则可以使用自己的替代方法定义自己的类型,并将其嵌入其中。*gin.Context*gin.Context
在实践中:
type MyGinContext struct {
*gin.Context
}
func (m *MyGinContext) BindJSON(obj interface{}) error {
fmt.Println("my own BindJSON")
return m.Context.BindJSON(obj) // or entirely alternative implementation
}
// Using the appropriate function signature now
func (repository *UrlRepo) CreateUrl(c *gin.Context) {
myCtx := &MyGinContext{c}
var url models.Url
_ = myCtx.BindJSON(&url) // will also print "my own BindJSON"
// ...
// other gin.Context methods are promoted and available on MyGinContext
myCtx.Status(200)
}
但老实说,我不确定为什么你会想要覆盖.如果要提供不同的绑定逻辑,甚至不同的呈现,可以实现库已公开的接口。例如:*gin.Context
实现绑定:
c.ShouldBindWith()将一个接口作为第二个参数,您可以实现该接口:binding.Binding
type MyBinder struct {
}
func (m *MyBinder) Name() string {
return "foo"
}
func (m *MyBinder) Bind(*http.Request, interface{}) error {
// stuff
return nil
}
func MyHandler(c *gin.Context) {
var foo struct{/*fields*/}
c.ShouldBindWith(&foo, &MyBinder{})
}
实现渲染器:
type MyRenderer struct {
}
type Render interface {
func (m *MyRenderer) Render(http.ResponseWriter) error {
// ...
return nil
}
func (m *MyRenderer) WriteContentType(w http.ResponseWriter) {
header := w.Header()
if val := header["Content-Type"]; len(val) == 0 {
header["Content-Type"] = "application/foo+bar"
}
}
func MyHandler(c *gin.Context) {
c.Render(200, &MyRenderer{})
}

TA贡献2037条经验 获得超6个赞
如果您用作 http 路由器,则入口点的参数应为 .gin-gonic
*gin.Context
因此,例如,您应该替换以下内容:
func (repository *UrlRepo) CreateUrl(c Icontext) {
有了这个
func (repository *UrlRepo) CreateUrl(c *gin.Context) {
这样,您应该能够使用模拟杜松子酒上下文作为单元测试的参数
- 2 回答
- 0 关注
- 114 浏览
添加回答
举报