Skip to content

Commit

Permalink
merge code and refactoring unit test
Browse files Browse the repository at this point in the history
  • Loading branch information
ktm-m committed May 18, 2024
1 parent 984045b commit 65fd615
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 87 deletions.
99 changes: 25 additions & 74 deletions api/expense/handler_test.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
package get
package expense

import (
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/labstack/echo/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"net/http"
"net/http/httptest"
"testing"
)

// Define a mock service implementing the Service interface
type MockService struct {
mock.Mock
}

func (m *MockService) GetAll(filter Filter, paginate Paginate) ([]Expense, error) {
func (m *MockService) GetAll(filter Filter, paginate Pagination) ([]Expense, error) {
args := m.Called(filter, paginate)
if args.Get(0) == nil {
return nil, args.Error(1)
Expand All @@ -25,79 +23,32 @@ func (m *MockService) GetAll(filter Filter, paginate Paginate) ([]Expense, error
}

func TestHandler_GetAll(t *testing.T) {
// Arrange
e := echo.New()
req := httptest.NewRequest(http.MethodGet, "/expenses", nil)
rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

mockService := new(MockService)
h := NewHandler(mockService)
c.Set("filter", Filter{})
c.Set("paginate", Pagination{})

tests := []struct {
name string
queryParams map[string]string
expectedStatus int
expectedBody string
setupMock func()
}{
expected := []Expense{
{
name: "valid request with all parameters",
queryParams: map[string]string{
"date": "2022-01-01",
"amount": "123.45",
"category": "test-category",
"itemPerPage": "5",
"page": "2",
},
expectedStatus: http.StatusOK,
expectedBody: `[{"id":1,"amount":200, "date":null, "category":"category1", "imageUrl":"urlOne", "note":"note", "spenderId":"1"}]`,
setupMock: func() {
date, _ := time.Parse("2006-01-02", "2022-01-01")
amount := float32(123.45)
filter := Filter{
Date: &date,
Amount: &amount,
Category: "test-category",
}
pagination := Paginate{
ItemPerPage: 5,
Page: 2,
}
mockService.On("GetAll", filter, pagination).Return([]Expense{{ID: 1, Date: nil, Amount: 200, Category: "category1", ImageUrl: "urlOne", Note: "note", SpenderId: "1"}}, nil)
},
ID: 1,
Amount: float32(2000.0),
Date: nil,
Category: "food",
ImageUrl: "http://img.png",
Note: "expense note",
SpenderId: "1",
},
// {
// name: "invalid date format",
// queryParams: map[string]string{
// "date": "invalid-date",
// },
// expectedStatus: http.StatusBadRequest,
// expectedBody: `"Invalid date format: parsing time "invalid-date" as "2006-01-02": cannot parse "invalid-date" as "2006"`,
// setupMock: func() {},
// },
// Add more test cases as needed
}

// Act
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.setupMock()

req := httptest.NewRequest(http.MethodGet, "/", nil)
q := req.URL.Query()
for k, v := range tt.queryParams {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()

rec := httptest.NewRecorder()
c := e.NewContext(req, rec)

// Assert
if assert.NoError(t, h.GetAll(c)) {
assert.Equal(t, tt.expectedStatus, rec.Code)
assert.JSONEq(t, tt.expectedBody, rec.Body.String())
}
mockService := new(MockService)
mockService.On("GetAll", mock.Anything, mock.Anything).Return(expected, nil).Once()
h := NewHandler(mockService)

mockService.AssertExpectations(t)
})
}
err := h.GetAll(c)
assert.NoError(t, err)
assert.Equal(t, http.StatusOK, rec.Code)
mockService.AssertExpectations(t)
}
4 changes: 2 additions & 2 deletions api/expense/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ func (r repository) GetAll(filter Filter, paginate Pagination) ([]Expense, error
conditions = append(conditions, fmt.Sprintf("date = $%d", len(args)+1))
args = append(args, filter.Date)
}
if filter.Amount != nil {
if filter.Amount != 0 {
conditions = append(conditions, fmt.Sprintf("amount = $%d", len(args)+1))
args = append(args, *filter.Amount)
args = append(args, filter.Amount)
}
if filter.Category != "" {
conditions = append(conditions, fmt.Sprintf("category = $%d", len(args)+1))
Expand Down
10 changes: 5 additions & 5 deletions api/expense/repository_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package get
package expense

import (
"errors"
Expand All @@ -21,7 +21,7 @@ func TestGetAll_ShouldReturnError_WhenErrorOnPrepare(t *testing.T) {
mock.ExpectPrepare(`SELECT id, date, amount, category, image_url, note, spender_id FROM transaction LIMIT \$1 OFFSET \$2`).WillReturnError(errors.New("error on prepare"))
mockFilter := Filter{}

mockPaginate := Paginate{
mockPaginate := Pagination{
ItemPerPage: 1,
Page: 1,
}
Expand All @@ -44,7 +44,7 @@ func TestGetAll_ShouldReturnError_WhenErrorOnScan(t *testing.T) {
mock.ExpectPrepare(`SELECT id, date, amount, category, image_url, note, spender_id FROM transaction LIMIT \$1 OFFSET \$2`).ExpectQuery().WillReturnError(errors.New("error on scan"))
mockFilter := Filter{}

mockPaginate := Paginate{
mockPaginate := Pagination{
ItemPerPage: 1,
Page: 1,
}
Expand Down Expand Up @@ -76,11 +76,11 @@ func TestGetAll_ShouldReturnData_WhenCorrectInput(t *testing.T) {

mockFilter := Filter{
Date: &mockDate,
Amount: &mockAmount,
Amount: mockAmount,
Category: mockCategory,
}

mockPaginate := Paginate{
mockPaginate := Pagination{
ItemPerPage: 1,
Page: 1,
}
Expand Down
12 changes: 6 additions & 6 deletions api/expense/service_test.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package get
package expense

import (
"errors"
Expand All @@ -13,7 +13,7 @@ type MockRepository struct {
mock.Mock
}

func (m *MockRepository) GetAll(filter Filter, paginate Paginate) ([]Expense, error) {
func (m *MockRepository) GetAll(filter Filter, paginate Pagination) ([]Expense, error) {
args := m.Called(filter, paginate)
if args.Get(0) == nil {
return nil, args.Error(1)
Expand All @@ -32,11 +32,11 @@ func TestService_GetAll_ShouldReturnError_WhenRepositoryReturnsError(t *testing.

mockFilter := Filter{
Date: &mockDate,
Amount: &mockAmount,
Amount: mockAmount,
Category: mockCategory,
}

mockPaginate := Paginate{
mockPaginate := Pagination{
ItemPerPage: 2,
Page: 1,
}
Expand Down Expand Up @@ -65,11 +65,11 @@ func TestService_GetAll_ShouldReturnData_WhenRepositoryReturnsData(t *testing.T)

mockFilter := Filter{
Date: &mockDate,
Amount: &mockAmount,
Amount: mockAmount,
Category: mockCategory,
}

mockPaginate := Paginate{
mockPaginate := Pagination{
ItemPerPage: 2,
Page: 1,
}
Expand Down

0 comments on commit 65fd615

Please sign in to comment.