模拟Go-Echo上下文

模拟Go-Echo上下文,go,integration-testing,Go,Integration Testing,我正在测试Go echo的路由处理程序 代码如下所示: p := NewPoint(s.db) // Update the deduction and exchange rate. e := echo.New() mapD := map[string]string{"exchange_cash": "5", "exchange_point": "7"} mapB, _ := json.Marshal(mapD) req := httptest.NewRequest(echo.POST, "h

我正在测试Go echo的路由处理程序

代码如下所示:

p := NewPoint(s.db)

// Update the deduction and exchange rate.
e := echo.New()

mapD := map[string]string{"exchange_cash": "5", "exchange_point": "7"}
mapB, _ := json.Marshal(mapD)
req := httptest.NewRequest(echo.POST, "http://localhost:1323/settings/update/exchange", bytes.NewReader(mapB))
//req := httptest.NewRequest(echo.POST, "/settings/update/exchange", bytes.NewReader(mapB))
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

u := p.UpdateDeductionRate(c)
assert.Equal(s.T(), "success", u)
但这会导致出现“不支持的媒体类型”之类的错误

对于Get测试,代码如下

req := httptest.NewRequest(echo.GET, "http://localhost:1323/admin/user_points/settings/get", nil)
//req := httptest.NewRequest(echo.GET, "/admin/user_points/settings/get", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
g := p.GetRates(c)
assert.Equal(s.T(), "success", g)
g是零。看起来根本没有调用hander p.UpdateDeductionRate(c echo.Context)和p.GetRates(c echo.Context)


我感觉像是回声。上下文构造不正确。有人知道吗?谢谢

问题可能是您在传递json编码的数据时没有指定
内容类型

req.Header.Set(echo.HeaderContentType,echo.MIMEApplicationJSON)
添加到您的代码中,它应该可以工作:

req := httptest.NewRequest(echo.GET, "http://localhost:1323/admin/user_points/settings/get", nil)
req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)

rec := httptest.NewRecorder()

c := e.NewContext(req, rec)
g := p.GetRates(c)

assert.Equal(s.T(), "success", g)