Test response from handler


#1

I want to test a JSON response from one of my handlers. I can’t figure it out from the sample test code on the testing section how to do this. The db seems to be mocked as a handler which confuses me, I don’t have a db or anything, I literally just send through some query params and then return some JSON which I want to test.

This is my handler code.

// CreateWallet initialises a user wallet based on one coin and some initial units
func CreateWallet(c echo.Context) error {
	coinMap := make(map[string]int)
	coin := c.QueryParam("coin")
	units, err := strconv.Atoi(c.QueryParam("units"))
	if err != nil {
		fmt.Println("error creating wallet")
	}
	coinMap[coin] = units
	btcWallet := wallet.NewWallet(coinMap)
	return c.JSON(http.StatusCreated, btcWallet)
}

Does anyone know how I can simply hit the path which is /createWallet and then check the response is the correct JSON?


#2

Code below might be useful for you, for details check out test cases in the repository (https://github.com/labstack/echo/blob/master/middleware/key_auth_test.go)

req := httptest.NewRequest(echo.GET, "/", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)
q := req.URL.Query()
q.Add("units", "value")
req.URL.RawQuery = q.Encode()
if assert.NoError(t, CreateWallet(c)) {
  assert.Equal(t, http.StatusOK, rec.Code)
  assert.Contains(t, rec.Body.String(), "<YOUR_JSON_STRING>")
}

#3

Amazing, thanks for the help, works perfectly.