我将echo框架与自定义上下文一起使用:ApiContext struct { echo.Context UserID int64 UserRole string}我的中间件:e.Use(func(h echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { cc := &common.ApiContext{c, 0, ""} return h(cc) }})我的处理程序:func (app *App) listEntity(c echo.Context) error { ctx := c.(*ApiContext) // error!....}我的测试:func TestlistEntity(t *testing.T){ e := echo.New() req := httptest.NewRequest(echo.GET, "/", nil) rec := httptest.NewRecorder() c := e.NewContext(req, rec) c.SetPath("/api/v1/entity/list") if assert.NoError(t, EntityList(c)) { assert.Equal(t, http.StatusOK rec.Code) }}我收到这个错误:恐慌:接口转换:echo.Context 是 *echo.context,不是 *common.ApiContext在处理程序函数类型断言中如何正确编写测试?附言。这种方法工作正常。
2 回答

慕无忌1623718
TA贡献1744条经验 获得超4个赞
所以这个方法不是很好,什么时候可以panic。您可以非常简单地捕获该错误:
ctx, ok := c.(*ApiContext)
if !ok {
// do something when you have a different type
// return an error here
}
我认为您不应该使用不同的上下文echo.Context,因为只有使用该上下文才能支持测试。
但回到你的问题。如果你想用你的上下文来测试它,你需要将你的上下文传递给测试而不是echo.Context.

Smart猫小萌
TA贡献1911条经验 获得超7个赞
前:
if assert.NoError(t, EntityList(c)) {
assert.Equal(t, http.StatusOK rec.Code)
}
之后(字面上放在您的自定义上下文中):
if assert.NoError(t, EntityList(&common.ApiContext{c, 0, ""})) {
assert.Equal(t, http.StatusOK rec.Code)
}
但是,使用标准context.Context是更好的做法。
- 2 回答
- 0 关注
- 111 浏览
添加回答
举报
0/150
提交
取消