Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork2.3k
How to make path params work in unit tests without having to add in request struct?#2714
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
am using echo v4.12.0 and am facing this issue in unit tests. as a workaround, i need to add the param in the request struct in the unit test or add reference to setting path params in test:https://echo.labstack.com/docs/testing#setting-path-params |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 1 comment 2 replies
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
request struct: if I add unit test like this, it fails because c.Bind() doesn't work as expected for the path params; json params work as expected. |
BetaWas this translation helpful?Give feedback.
All reactions
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
having to update request struct in test as a workaround. |
BetaWas this translation helpful?Give feedback.
All reactions
-
The problem is that typeReqstruct {TestParamOnestring`param:"test_param_one"`TestParamTwostring`param:"test_param_two"`TestJsonOnestring`json:"test_json_param"`}payload:=Req{TestJsonOne:"json1",}varbuf bytes.Bufferiferr:=json.NewEncoder(&buf).Encode(payload);err!=nil {t.Fatal(err)}fmt.Printf(buf.String()) will result to body being and when it comes to binding - json fields will overwrite path fields. This test would work as it passes json body without these fields as empty to request package mainimport ("bytes""github.com/labstack/echo/v4""net/http""net/http/httptest""testing")funcTestName(t*testing.T) {typeReqstruct {TestParamOnestring`param:"test_param_one"`TestParamTwostring`param:"test_param_two"`TestJsonOnestring`json:"test_json_param"`}req:=httptest.NewRequest(http.MethodPost,"/test/:test_param_one/:test_param_two",bytes.NewBuffer([]byte(`{"test_json_param":"json1"}`)))req.Header.Set(echo.HeaderContentType,echo.MIMEApplicationJSON)rec:=httptest.NewRecorder()e:=echo.New()c:=e.NewContext(req,rec)c.SetParamNames("test_param_one","test_param_two")c.SetParamValues("param1","param2")handler:=func(c echo.Context)error {payload:=Req{}iferr:=c.Bind(&payload);err!=nil {returnerr}returnc.JSON(http.StatusOK,payload)}err:=handler(c)iferr!=nil {t.Fatal(err)}body:=rec.Body.String()if"{\"TestParamOne\":\"param1\",\"TestParamTwo\":\"param2\",\"test_json_param\":\"json1\"}\n"!=body {t.Errorf("unexpected response, got: %s",body)}} |
BetaWas this translation helpful?Give feedback.