I use echo framework with Custom Context:
ApiContext struct {
echo.Context
UserID int64
UserRole string
}
my middleware:
e.Use(func(h echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
cc := &common.ApiContext{c, 0, ""}
return h(cc)
}
})
my handler:
func (app *App) listEntity(c echo.Context) error {
ctx := c.(*ApiContext) // error!
....
}
my test:
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)
}
}
i got this error:
panic: interface conversion: echo.Context is *echo.context, not *common.ApiContext
in handler function type assertion
How correctly to write the test? ps. this method working fine.
So the method is not really fine, when it can panic. You could catch that error very simple:
ctx, ok := c.(*ApiContext)
if !ok {
// do something when you have a different type
// return an error here
}
I think you should not use a different context then echo.Context
, because just with that context the testing is supported.
But back to your question. If you want to test it with your context you need to pass your context into the test and not the echo.Context
.