我將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 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消