|
| 1 | +package service |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "example.com/clean-arch/entity" |
| 7 | + "github.com/stretchr/testify/assert" |
| 8 | + "github.com/stretchr/testify/mock" |
| 9 | +) |
| 10 | + |
| 11 | +func TestValidateEmptyPost(t *testing.T) { |
| 12 | + testService := NewPostService(nil) |
| 13 | + |
| 14 | + err := testService.Validate(nil) |
| 15 | + |
| 16 | + assert.NotNil(t, err) |
| 17 | + assert.Equal(t, "the post is empty", err.Error()) |
| 18 | +} |
| 19 | + |
| 20 | +type MockRepository struct { |
| 21 | + mock.Mock |
| 22 | +} |
| 23 | + |
| 24 | +func (mock *MockRepository) Save(post *entity.Post) (*entity.Post, error) { |
| 25 | + args := mock.Called() |
| 26 | + result := args.Get(0) |
| 27 | + return result.(*entity.Post), args.Error(1) |
| 28 | +} |
| 29 | + |
| 30 | +func (mock *MockRepository) FindAll() ([]entity.Post, error) { |
| 31 | + args := mock.Called() |
| 32 | + result := args.Get(0) |
| 33 | + return result.([]entity.Post), args.Error(1) |
| 34 | +} |
| 35 | + |
| 36 | +func TestValidateEmptyPostTitle(t *testing.T) { |
| 37 | + post := entity.Post{ |
| 38 | + ID: 1, |
| 39 | + Title: "", |
| 40 | + Text: "B", |
| 41 | + } |
| 42 | + |
| 43 | + testService := NewPostService(nil) |
| 44 | + |
| 45 | + err := testService.Validate(&post) |
| 46 | + |
| 47 | + assert.NotNil(t, err) |
| 48 | + assert.Equal(t, "the post title is empty", err.Error()) |
| 49 | +} |
| 50 | + |
| 51 | +func TestFindAll(t *testing.T) { |
| 52 | + mockRepo := new(MockRepository) |
| 53 | + |
| 54 | + var identifier int64 = 1 |
| 55 | + |
| 56 | + post := entity.Post{ |
| 57 | + ID: identifier, |
| 58 | + Title: "A", |
| 59 | + Text: "B", |
| 60 | + } |
| 61 | + // Setup expectations |
| 62 | + mockRepo.On("FindAll").Return([]entity.Post{post}, nil) |
| 63 | + |
| 64 | + testService := NewPostService(mockRepo) |
| 65 | + |
| 66 | + result, _ := testService.FindAll() |
| 67 | + |
| 68 | + // Mock Assertion: Behavioral |
| 69 | + mockRepo.AssertExpectations(t) |
| 70 | + |
| 71 | + // Data Assertion |
| 72 | + assert.Equal(t, identifier, result[0].ID) |
| 73 | + assert.Equal(t, "A", result[0].Title) |
| 74 | + assert.Equal(t, "B", result[0].Text) |
| 75 | +} |
| 76 | + |
| 77 | +func TestCreate(t *testing.T) { |
| 78 | + mockRepo := new(MockRepository) |
| 79 | + |
| 80 | + post := entity.Post{ |
| 81 | + Title: "A", |
| 82 | + Text: "B", |
| 83 | + } |
| 84 | + // Setup expectations |
| 85 | + mockRepo.On("Save").Return(&post, nil) |
| 86 | + |
| 87 | + testService := NewPostService(mockRepo) |
| 88 | + |
| 89 | + result, err := testService.Create(&post) |
| 90 | + |
| 91 | + mockRepo.AssertExpectations(t) |
| 92 | + |
| 93 | + assert.NotNil(t, result.ID) |
| 94 | + assert.Equal(t, "A", result.Title) |
| 95 | + assert.Equal(t, "B", result.Text) |
| 96 | + assert.Nil(t, err) |
| 97 | +} |
0 commit comments