I'm trying to test a route handler of Go echo.
Code looks like following:
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)
Yet this keeps give error like "Unsupported Media Type"
For Get test, code is like
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 is nil. It looks like the hander p.UpdateDeductionRate(c echo.Context), p.GetRates(c echo.Context) is not called at all.
I feel like the echo.Context is not constructed correctly. Anyone has idea? Thanks!
The problem is probably that you are passing json-encoded data without specifying the Content-Type
header.
Add req.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
to your code, and it should work:
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)