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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘