Skip to content

Commit

Permalink
Handler tests
Browse files Browse the repository at this point in the history
  • Loading branch information
Taras.Hots committed Mar 16, 2024
1 parent 1c72ea7 commit 919467b
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 3 deletions.
4 changes: 1 addition & 3 deletions handlers/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
62 changes: 62 additions & 0 deletions tests/integration/todo_handler_test.go
Original file line number Diff line number Diff line change
@@ -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"))
}
}

0 comments on commit 919467b

Please sign in to comment.