diff --git a/handlers/handler.go b/handlers/handler.go index 0d79f5a..0f8708f 100644 --- a/handlers/handler.go +++ b/handlers/handler.go @@ -25,9 +25,7 @@ func (handler *TodoHandler) GetAllTodos(c echo.Context) error { } func (handler *TodoHandler) GetById(c echo.Context) error { - id := c.QueryParam("id") - - return c.JSON(http.StatusOK, json.NewEncoder(c.Response().Writer).Encode(handler.store.GetById(id))) + return c.JSON(http.StatusOK, handler.store.GetById(c.Param("id"))) } func (handler *TodoHandler) AddOrUpdateTodo(c echo.Context) error { diff --git a/tests/integration/todo_handler_test.go b/tests/integration/todo_handler_test.go new file mode 100644 index 0000000..fbf80b1 --- /dev/null +++ b/tests/integration/todo_handler_test.go @@ -0,0 +1,62 @@ +package handler + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + handler "th/GoDoIt/handlers" + "th/GoDoIt/models" + "th/GoDoIt/storage" + + "github.com/labstack/echo/v4" + "github.com/stretchr/testify/assert" +) + +func TestEmptyTodoList(t *testing.T) { + e := echo.New() + request := httptest.NewRequest(http.MethodGet, "/todo", nil) + recorder := httptest.NewRecorder() + context := e.NewContext(request, recorder) + + storage := storage.New() + handler := handler.New(storage) + + expectedResponseBody := "[]" + + if assert.NoError(t, handler.GetAllTodos(context)) { + assert.Equal(t, http.StatusOK, recorder.Code) + assert.Equal(t, expectedResponseBody, strings.TrimSuffix(recorder.Body.String(), "\n")) + } +} + +func TestCanGetById(t *testing.T) { + e := echo.New() + request := httptest.NewRequest(http.MethodGet, "/", nil) + + recorder := httptest.NewRecorder() + context := e.NewContext(request, recorder) + context.SetPath("/todo/:id") + context.SetParamNames("id") + context.SetParamValues("1") + + var exampleTodoItem models.Todo + exampleTodoItem.ID = "1" + exampleTodoItem.Title = "test" + exampleTodoItem.Description = "test desc" + exampleTodoItem.DueDate = time.Now() + + expectedJson, _ := json.Marshal(exampleTodoItem) + + storage := storage.New() + storage.Add(&exampleTodoItem) + handler := handler.New(storage) + + if assert.NoError(t, handler.GetById(context)) { + assert.Equal(t, http.StatusOK, recorder.Code) + assert.Equal(t, string(expectedJson), strings.TrimSuffix(recorder.Body.String(), "\n")) + } +}