|
| 1 | +package repository_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/amitshekhariitbhu/go-backend-clean-architecture/domain" |
| 9 | + "github.com/amitshekhariitbhu/go-backend-clean-architecture/mongo/mocks" |
| 10 | + "github.com/amitshekhariitbhu/go-backend-clean-architecture/repository" |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | + "github.com/stretchr/testify/mock" |
| 13 | + "go.mongodb.org/mongo-driver/bson/primitive" |
| 14 | +) |
| 15 | + |
| 16 | +func TestCreate(t *testing.T) { |
| 17 | + |
| 18 | + var databaseHelper *mocks.Database |
| 19 | + var collectionHelper *mocks.Collection |
| 20 | + |
| 21 | + databaseHelper = &mocks.Database{} |
| 22 | + collectionHelper = &mocks.Collection{} |
| 23 | + |
| 24 | + collectionName := domain.CollectionUser |
| 25 | + |
| 26 | + mockUser := &domain.User{ |
| 27 | + ID: primitive.NewObjectID(), |
| 28 | + Name: "Test", |
| 29 | + |
| 30 | + Password: "password", |
| 31 | + } |
| 32 | + |
| 33 | + mockEmptyUser := &domain.User{} |
| 34 | + mockUserID := primitive.NewObjectID() |
| 35 | + |
| 36 | + t.Run("success", func(t *testing.T) { |
| 37 | + |
| 38 | + collectionHelper.On("InsertOne", mock.Anything, mock.AnythingOfType("*domain.User")).Return(mockUserID, nil).Once() |
| 39 | + |
| 40 | + databaseHelper.On("Collection", collectionName).Return(collectionHelper) |
| 41 | + |
| 42 | + ur := repository.NewUserRepository(databaseHelper, collectionName) |
| 43 | + |
| 44 | + err := ur.Create(context.Background(), mockUser) |
| 45 | + |
| 46 | + assert.NoError(t, err) |
| 47 | + |
| 48 | + collectionHelper.AssertExpectations(t) |
| 49 | + }) |
| 50 | + |
| 51 | + t.Run("error", func(t *testing.T) { |
| 52 | + collectionHelper.On("InsertOne", mock.Anything, mock.AnythingOfType("*domain.User")).Return(mockEmptyUser, errors.New("Unexpected")).Once() |
| 53 | + |
| 54 | + databaseHelper.On("Collection", collectionName).Return(collectionHelper) |
| 55 | + |
| 56 | + ur := repository.NewUserRepository(databaseHelper, collectionName) |
| 57 | + |
| 58 | + err := ur.Create(context.Background(), mockEmptyUser) |
| 59 | + |
| 60 | + assert.Error(t, err) |
| 61 | + |
| 62 | + collectionHelper.AssertExpectations(t) |
| 63 | + }) |
| 64 | + |
| 65 | +} |
0 commit comments