Testify with echo giving error in context conversion

I have created APIS using echo and i wanted to test it using testify but when i am trying to run it it does not allow me , I am pasting my code below please correct me if i am doing something wrong

API to test

type WebContext struct {
echo.Context
Registry
sess *sessions.Session
}
func GetWebContext(c echo.Context) *WebContext {
return c.(*WebContext)
}

func EmailTemplateDelete(c echo.Context) error {
wc := core.GetWebContext©
r := model.NewSuccessResponse()

    u, err := service.GetUserForRequest(wc)
    if err != nil {
     return wc.JSON(http.StatusUnauthorized, model.NewErrorResponse("error in fetching user details"))
     }
    return c.JSON(http.StatusOK, r)

}

code I am using for testify

func TestEmailTemplateDelete(t *testing.T) {
// Setup
e := echo.New()
req := httptest.NewRequest(http.MethodGet, “/”, nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
c.SetPath("/api/v1/emai_template")
if assert.NoError(t, EmailTemplateDelete©) {
assert.Equal(t, http.StatusOK, rec.Code)
//assert.Equal(t, userJSON, strings.TrimSpace(rec.Body.String()))
}

When I am doing go test email_template.go email_template_test.go
It throws an error

— FAIL: TestEmailTemplateDelete (0.00s)
panic: interface conversion: echo.Context is *echo.context, not *core.WebContext [recovered]
panic: interface conversion: echo.Context is *echo.context, not *core.WebContext

Please make me correct If I am doing any silly mistake as I am new to Golang

Thanks in Advance

You can’t cast embedded type to parent type.

Thanks Ali for your response , do you have any idea that how we can do it , I mean how we can write the unit test for the APIS where we are using echo context ?

I hope this will help:
Change this

with this:

func GetWebContext(c echo.Context) *WebContext {
return &WebContext{Context:c}
}
1 Like

Thanks a lot Ali, it is working for me :slight_smile:

1 Like