package api import ( "log" "net/http" "net/http/httptest" "strings" "testing" "time" "github.com/DATA-DOG/go-sqlmock" "github.com/labstack/echo/v4" ) func TestGetTransactions(t *testing.T) { db, mock, err := sqlmock.New() if err != nil { t.Fatal(err) } e := echo.New() handlers := ServerImpl{db} RegisterHandlers(e, &handlers) t.Run("when successful", func(t *testing.T) { rec := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "/transactions", nil) date := time.Now() rows := mock.NewRows([]string{"category", "date", "description", "id", "amount"}). AddRow(nil, date, "#1", 1, 1000). AddRow("expense", date, "#2", 2, -1000) mock.ExpectQuery("SELECT t.category, t.date, t.description, t.id, tc.amount FROM pfbudget.transactions t LEFT JOIN pfbudget.transactions_categorized tc ON t.id = tc.id").WillReturnRows(rows) ctx := e.NewContext(req, rec) err := handlers.GetTransactions(ctx, GetTransactionsParams{}) if err != nil { t.Error(err) } if rec.Code != http.StatusOK { t.Error(rec.Code) } expected := `[ { "date":"` + date.Format(time.DateOnly) + `", "description": "#1", "id":1, "value":1000 }, { "category": "expense", "date":"` + date.Format(time.DateOnly) + `", "description": "#2", "id":2, "value":-1000 } ]` expected = strings.Join(strings.Fields(expected), "") log.Println(expected) if ret := strings.TrimRight(rec.Body.String(), "\n"); ret != expected { t.Error(ret, expected) } }) }