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 關注
- 130 瀏覽
添加回答
舉報