duanchen7703 2018-08-13 16:56
浏览 55
已采纳

如何在echo中使用自定义上下文正确测试处理程序?

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.

  • 写回答

1条回答 默认 最新

  • duancan8382 2018-08-13 19:27
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失
  • ¥15 springboot+vue 集成keycloak sso到阿里云
  • ¥15 win7系统进入桌面过一秒后突然黑屏
  • ¥30 backtrader对于期货交易的现金和资产计算的问题
  • ¥15 求C# .net4.8小报表工具
  • ¥15 安装虚拟机时出现问题
  • ¥15 Selenium+docker Chrome不能运行
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到