public void ShouldThrowAnExceptionWhenUserAlreadyExists()
        {
            #region Given

            string userId          = UserIdMother.Id();
            string expectedMessage = $"The user '{userId}' already exists";
            User   user            = UserMother.User(userId);

            var userRepository = new Mock <UserRepository>();

            userRepository
            .Setup(r => r.Find(It.IsAny <UserId>()))
            .ReturnsAsync(UserMother.User(userId));

            userRepository
            .Setup(r => r.Exists(It.IsAny <UserId>()))
            .ReturnsAsync(true);

            userRepository
            .Setup(r => r.Save(It.IsAny <User>()));

            UserCreator userCreator = new UserCreator(userRepository.Object);

            #endregion

            #region When
            var exception = Record.ExceptionAsync(async() => await userCreator.Execute(user));

            #endregion

            #region Then
            Assert.Equal(expectedMessage, exception.Result.Message);

            #endregion
        }
        public async Task GetPokemonFavorites_ReturnsPokemonFavorites()
        {
            #region Arrange
            string           id               = UserIdMother.Id();
            UserId           userId           = UserIdMother.UserId();
            int              pokemonId        = PokemonIdMother.Id();
            PokemonFavorites pokemonFavorites = PokemonFavoritesMother.PokemonFavorites();

            var userRepository = new Mock <UserRepository>();

            userRepository
            .Setup(r => r.Find(It.IsAny <UserId>()))
            .ReturnsAsync(UserMother.UserWithFavorites(id, pokemonId));

            userRepository
            .Setup(r => r.Exists(It.IsAny <UserId>()))
            .ReturnsAsync(true);

            UserFinder userFinder = new UserFinder(userRepository.Object);
            PokemonFavoriteSearcher pokemonFavoriteSearcher = new PokemonFavoriteSearcher();
            GetPokemonUserFavorites getPokemonUserFavorites = new GetPokemonUserFavorites(userFinder, pokemonFavoriteSearcher);

            #endregion

            #region Act
            PokemonFavorites favorites = await getPokemonUserFavorites.Execute(id);

            #endregion

            #region Assert
            Assert.True(pokemonFavorites.Favorites.All(f => favorites.Favorites.Any(item =>
                                                                                    item.PokemonId.Id == f.PokemonId.Id)));

            #endregion
        }
Example #3
0
        public void SaveRepositoryNameChanged()
        {
            var repository = new UserMongoRepository(GetRequiredService <IOptions <MongoSettings> >());

            var roberto = UserMother.Create();

            for (var i = 0; i < 10; i++)
            {
                roberto.AddAddress(AddressMother.Create());
            }

            for (var i = 0; i < 5; i++)
            {
                roberto.AddEmail(EmailMother.Create());
            }

            repository.Add(roberto);

            repository.SaveChanges();

            var repository2 = new UserMongoRepository(GetRequiredService <IOptions <MongoSettings> >());
            var repoUser    = repository2.GetById(roberto.Id);

            Assert.Equal(roberto.Id, repoUser.Id);
            Assert.Equal(roberto.Name, repoUser.Name);
            Assert.Equal(5, repoUser.Emails.Count());
            Assert.Equal(10, repoUser.Addresses.Count());
        }
Example #4
0
        public void CreateUser_ReturnsUserAlreadyExistsException()
        {
            #region Arrange
            string userId          = UserIdMother.Id();
            string expectedMessage = $"The user '{userId}' already exists";

            var userRepository = new Mock <UserRepository>();

            userRepository
            .Setup(r => r.Find(It.IsAny <UserId>()))
            .ReturnsAsync(UserMother.User(userId));

            userRepository
            .Setup(r => r.Exists(It.IsAny <UserId>()))
            .ReturnsAsync(true);

            userRepository
            .Setup(r => r.Save(It.IsAny <User>()));

            UserCreator userCreator = new UserCreator(userRepository.Object);
            CreateUser  createUser  = new CreateUser(userCreator);

            #endregion

            #region Act
            var exception = Record.ExceptionAsync(async() => await createUser.Execute(userId));

            #endregion

            #region Assert
            Assert.Equal(expectedMessage, exception.Result.Message);

            #endregion
        }
        public async Task AddPokemonToUserFavorites_ReturnsVoid()
        {
            #region Arrange
            int    pokemonId      = PokemonIdMother.Id();
            string userId         = UserIdMother.Id();
            var    userRepository = new Mock <UserRepository>();

            userRepository
            .Setup(r => r.Find(It.IsAny <UserId>()))
            .ReturnsAsync(UserMother.User(userId));

            userRepository
            .Setup(r => r.Exists(It.IsAny <UserId>()))
            .ReturnsAsync(true);

            userRepository
            .Setup(r => r.SaveFavorites(It.IsAny <User>()));

            UserFinder                userFinder                = new UserFinder(userRepository.Object);
            PokemonFavoriteCreator    pokemonFavoriteCreator    = new PokemonFavoriteCreator(userRepository.Object);
            AddPokemonToUserFavorites addPokemonToUserFavorites = new AddPokemonToUserFavorites(userFinder, pokemonFavoriteCreator);

            #endregion

            #region Act
            await addPokemonToUserFavorites.Execute(userId, pokemonId);

            #endregion

            #region Assert
            userRepository.Verify(r => r.SaveFavorites(It.IsAny <User>()), Times.Once());
            #endregion
        }
Example #6
0
        public void ShouldThrowAnExceptionWhenPokemonFavoriteAlreadyExists()
        {
            #region Given

            PokemonId       pokemonId       = PokemonIdMother.PokemonId();
            PokemonFavorite pokemonFavorite = new PokemonFavorite(pokemonId);
            string          userId          = UserIdMother.Id();
            string          expectedMessage = $"The pokemon with Id '{pokemonId.Id}' already exists in user favorites list";
            User            user            = UserMother.UserWithFavorites(userId, pokemonId.Id);

            var userRepository = new Mock <UserRepository>();

            userRepository
            .Setup(r => r.Find(It.IsAny <UserId>()))
            .ReturnsAsync(UserMother.UserWithFavorites(userId, pokemonId.Id));

            userRepository
            .Setup(r => r.SaveFavorites(It.IsAny <User>()));

            PokemonFavoriteCreator pokemonFavoriteCreator = new PokemonFavoriteCreator(userRepository.Object);

            #endregion

            #region When
            var exception = Record.ExceptionAsync(async() => await pokemonFavoriteCreator.Execute(user, pokemonFavorite));

            #endregion

            #region Then
            Assert.Equal(expectedMessage, exception.Result.Message);

            #endregion
        }
        public async Task ShouldCreateUser()
        {
            #region Given
            string userId         = UserIdMother.Id();
            User   user           = UserMother.User(userId);
            var    userRepository = new Mock <UserRepository>();

            userRepository
            .Setup(r => r.Save(It.IsAny <User>()));

            UserCreator userCreator = new UserCreator(userRepository.Object);

            #endregion

            #region When

            await userCreator.Execute(user);

            #endregion

            #region Then

            userRepository.Verify(r => r.Save(It.IsAny <User>()), Times.Once());

            #endregion
        }
Example #8
0
        private async Task LoadTestDataAsync(CancellationToken cancellationToken)
        {
            await using var dbContext = GetService <IDbContextFactory <SharedKernelDbContext> >().CreateDbContext();
            await dbContext.Database.EnsureDeletedAsync(cancellationToken);

            await dbContext.Database.MigrateAsync(cancellationToken);

            var repository = new UserEfCoreRepository(dbContext);

            var tasks = new List <Task>();

            for (var i = 0; i < 11; i++)
            {
                var roberto = UserMother.Create();

                for (var j = 0; j < 10; j++)
                {
                    roberto.AddAddress(AddressMother.Create());
                }

                for (var j = 0; j < 5; j++)
                {
                    roberto.AddEmail(EmailMother.Create());
                }

                tasks.Add(repository.AddAsync(roberto, cancellationToken));
            }

            await Task.WhenAll(tasks);

            await repository.SaveChangesAsync(cancellationToken);
        }
        private static Mock <IUserRepository> GetRepositoryMock()
        {
            var repositoryMock = new Mock <IUserRepository>();

            repositoryMock.Setup(m => m.GetUser(It.IsAny <UserUuid>())).Returns(UserMother.BasicUser());

            repositoryMock.Setup(m => m.Delete(It.IsAny <User>()));
            return(repositoryMock);
        }
        protected override void Given()
        {
            base.Given();

            var model = UserMother.Simple();

            _model = SUT.AddAsync(AdminUserId, model).Result;
            Assert.IsNotNull(SUT.GetAsync(AdminUserId, _model.Id).Result);
        }
Example #11
0
        public static async Task PublishDomainEvent(IEventBus eventBus, PublishUserCreatedDomainEvent singletonValueContainer, int millisecondsDelay)
        {
            var user = UserMother.Create();

            await eventBus.Publish(user.PullDomainEvents(), CancellationToken.None).ConfigureAwait(false);

            await Task.Delay(millisecondsDelay, CancellationToken.None).ConfigureAwait(false);

            Assert.Equal(user.Id, singletonValueContainer.UserId);
            Assert.True(singletonValueContainer.Total >= 2);
        }
        protected override void Given()
        {
            base.Given();

            _models = new List <User>
            {
                UserMother.Typical(),
                    UserMother.Typical()
            };

            _originalCount = SUT.CountAsync().Result;
        }
Example #13
0
        private static Mock <IUserRepository> GetRepositoryMock()
        {
            var repositoryMock = new Mock <IUserRepository>();

            var user = UserMother.BasicUser();

            user.HashedPassword = new HashedPassword("MyPasswordHashed--");

            repositoryMock.Setup(m => m.GetByEmail(It.IsAny <Email>())).Returns(user);

            return(repositoryMock);
        }
Example #14
0
        public void AddOk()
        {
            var mongoSettings = GetRequiredService <IOptions <MongoSettings> >();

            var repository = new UserMongoRepository(mongoSettings);

            var roberto = UserMother.Create();

            repository.Add(roberto);

            repository.SaveChanges();

            Assert.Equal(roberto, repository.GetById(roberto.Id));
        }
Example #15
0
        public static async Task PublishDomainEvent(InfrastructureTestCase testCase)
        {
            var httpContextAccessor = testCase.GetRequiredService <IHttpContextAccessor>();

            if (httpContextAccessor != default)
            {
#if !NET461 && !NETSTANDARD
                httpContextAccessor.HttpContext ??= new DefaultHttpContext();
#endif
                httpContextAccessor.HttpContext.User =
                    new ClaimsPrincipal(new ClaimsIdentity(new List <Claim> {
                    new Claim("Name", "Peter")
                }));
            }

            var user1 = UserMother.Create();
            var user2 = UserMother.Create();
            var user3 = UserMother.Create();
            var user4 = UserMother.Create();

            var domainEvents = user1.PullDomainEvents();
            domainEvents.AddRange(user2.PullDomainEvents());
            domainEvents.AddRange(user3.PullDomainEvents());
            domainEvents.AddRange(user4.PullDomainEvents());

            var       eventBus = testCase.GetRequiredService <IEventBus>();
            var       tasks    = new List <Task>();
            const int total    = 5;
            for (var i = 0; i < total; i++)
            {
                tasks.Add(eventBus.Publish(domainEvents, CancellationToken.None));
            }

            await Task.WhenAll(tasks);

            // Esperar a que terminen los manejadores de los eventos junto con la polĂ­tica de reintentos
            await Task.Delay(5_000, CancellationToken.None);

            var singletonValueContainer = testCase.GetRequiredService <PublishUserCreatedDomainEvent>();
            singletonValueContainer.Total.Should().Be(total * 4);

            singletonValueContainer.Users.Should().Contain(u => u == user1.Id);
            singletonValueContainer.Users.Should().Contain(u => u == user2.Id);
            singletonValueContainer.Users.Should().Contain(u => u == user3.Id);
            singletonValueContainer.Users.Should().Contain(u => u == user4.Id);
        }
        private static Mock <IUserRepository> GetRepositoryMock()
        {
            var repositoryMock = new Mock <IUserRepository>();

            var user = UserMother.BasicUser();

            user.HashedPassword = new HashedPassword("MyOldPasswordHashed--");

            repositoryMock.Setup(m => m.GetByEmail(It.IsAny <Email>())).Returns(user);

            repositoryMock.Setup(m => m.UpdatePassword(It.IsAny <User>(), It.IsAny <HashedPassword>())).Callback(
                (User existentUser, HashedPassword password) =>
            {
                Assert.AreEqual("MyNewPasswordHashed--", password.Value);
                Assert.AreEqual(1, user.DomainEvents.Count);
            });
            return(repositoryMock);
        }
        public async Task SaveRepositoryOk()
        {
            var dbContext = GetRequiredService <SharedKernelDbContext>();
            await dbContext.Database.EnsureDeletedAsync();

            await dbContext.Database.MigrateAsync();

            var repository = GetRequiredService <UserEfCoreRepository>();

            var roberto = UserMother.Create();

            repository.Add(roberto);

            await repository.SaveChangesAsync(CancellationToken.None);

            Assert.Equal(roberto, repository.GetById(roberto.Id));

            await dbContext.Database.EnsureDeletedAsync();

            await dbContext.Database.MigrateAsync();
        }
        public async Task SaveRepositoryNameChanged()
        {
            var dbContext = GetService <SharedKernelDbContext>();
            await dbContext.Database.EnsureDeletedAsync();

            await dbContext.Database.MigrateAsync();

            var repository = GetRequiredService <UserEfCoreRepository>();

            var roberto = UserMother.Create();

            for (var i = 0; i < 10; i++)
            {
                roberto.AddAddress(AddressMother.Create());
            }

            for (var i = 0; i < 5; i++)
            {
                roberto.AddEmail(EmailMother.Create());
            }

            repository.Add(roberto);

            repository.SaveChanges();

            var repository2 = GetRequiredService <UserEfCoreRepository>();
            var repoUser    = repository2.GetById(roberto.Id);

            Assert.Equal(roberto.Id, repoUser.Id);
            Assert.Equal(roberto.Name, repoUser.Name);
            Assert.Equal(5, repoUser.Emails.Count());
            Assert.Equal(10, repoUser.Addresses.Count());

            await dbContext.Database.EnsureDeletedAsync();

            await dbContext.Database.MigrateAsync();
        }
        public void AddPokemonToUserFavorites_ReturnsPokemonAlreadyExistsException()
        {
            #region Arrange
            int    pokemonId       = PokemonIdMother.Id();
            string userId          = UserIdMother.Id();
            string expectedMessage = $"The pokemon with Id '{pokemonId}' already exists in user favorites list";

            var userRepository = new Mock <UserRepository>();

            userRepository
            .Setup(r => r.Find(It.IsAny <UserId>()))
            .ReturnsAsync(UserMother.UserWithFavorites(userId, pokemonId));

            userRepository
            .Setup(r => r.Exists(It.IsAny <UserId>()))
            .ReturnsAsync(true);

            userRepository
            .Setup(r => r.SaveFavorites(It.IsAny <User>()));

            UserFinder                userFinder                = new UserFinder(userRepository.Object);
            PokemonFavoriteCreator    pokemonFavoriteCreator    = new PokemonFavoriteCreator(userRepository.Object);
            AddPokemonToUserFavorites addPokemonToUserFavorites = new AddPokemonToUserFavorites(userFinder, pokemonFavoriteCreator);

            #endregion

            #region Act
            var exception = Record.ExceptionAsync(async() => await addPokemonToUserFavorites.Execute(userId, pokemonId));

            #endregion

            #region Assert
            Assert.Equal(expectedMessage, exception.Result.Message);

            #endregion
        }
        private static Mock <IUserRepository> GetRepositoryMock()
        {
            var repositoryMock = new Mock <IUserRepository>();

            repositoryMock.Setup(m => m.GetUser(It.IsAny <UserUuid>())).Returns(
                UserMother.BasicUser()
                );

            repositoryMock.Setup(m => m.Update(It.IsAny <User>())).Callback(
                ((User user) =>
            {
                Assert.IsNotEmpty(user.UserUuid.Value);
                Assert.AreEqual("*****@*****.**", user.Email.Value);
                Assert.AreEqual("TestModified", user.Name.Value);
                Assert.AreEqual("Test Surname Modified", user.Surname.Value);
                Assert.AreEqual(987234322, user.PhoneNumber.Value);
                Assert.AreEqual(12346, user.PostalCode.Value);
                Assert.AreEqual("fr", user.CountryCode.Value);
                Assert.False(user.IsSamePassword(new HashedPassword("testpass")));

                Assert.AreEqual(2, user.DomainEvents.Count);
            }));
            return(repositoryMock);
        }
Example #21
0
        protected override void Given()
        {
            base.Given();

            _model = UserMother.Typical();
        }