public async Task GivenValidUserCommand_WhenTheUsernameAndEmailAreUnique_ShouldReturnSuccessfulUserViewModelResponse() { // Arrange var createUserCommand = new CreateUserCommand { User = new UserRegistrationDto { Username = "******", Email = "*****@*****.**", Password = "******" } }; // Act var command = new CreateUserCommandHandler(_logger, UserManager, Context, Mapper, TokenService); var result = await command.Handle(createUserCommand, CancellationToken.None); // Assert result.ShouldNotBeNull(); result.ShouldBeOfType <UserViewModel>(); result.User.ShouldNotBeNull(); result.User.Username.ShouldBe(createUserCommand.User.Username); result.User.Email.ShouldBe(createUserCommand.User.Email); Context.Users.Single(u => u.UserName == createUserCommand.User.Username).ShouldNotBeNull(); }
public async Task CreateUserCommand_CustomerDataReturnNoNoExistsUserInfrastructureException() { //Arange var writeIRepositoryMoq = new Mock <IWriteIRepository>(); var readRepositoryMoq = new Mock <IReadRepository>(); readRepositoryMoq.Setup(f => f.Contains(It.IsAny <ISpecification <UserEntity> >())) .Returns(true); var config = new MapperConfiguration(cfg => cfg.AddProfile <NotifikationProfile>()); IMapper mapper = config.CreateMapper(); var command = new CreateUserCommand() { User = new UserDTO() { Email = "*****@*****.**", Name = "test" } }; var handler = new CreateUserCommandHandler(writeIRepositoryMoq.Object, readRepositoryMoq.Object, mapper); //Act Func <Task <UserDTO> > act = () => handler.Handle(command, new System.Threading.CancellationToken()); //Asert await act.Should().ThrowAsync <NoExistsUserInfrastructureException>(); }
public async Task Should_CreateUser() { var request = FakeRequest(); var tenant = new TenantFake().Builder .RuleFor(x => x.Code, f => request.TenantCode) .Generate(); var role = new RoleFake().Builder .RuleFor(x => x.Code, f => request.RoleCode) .Generate(); var uowGeneralMock = new Mock <IUowGeneral>(); uowGeneralMock.Setup(x => x.UserRepository.FindByEmail(request.Email)).ReturnsAsync(default(User)); uowGeneralMock.Setup(x => x.TenantRepository.FindByCode(request.TenantCode)).ReturnsAsync(tenant); uowGeneralMock.Setup(x => x.RoleRepository.FindByCode(request.RoleCode)).ReturnsAsync(role); var passwordServiceMock = new Mock <IPasswordService>(); var handler = new CreateUserCommandHandler(uowGeneralMock.Object, passwordServiceMock.Object); var user = await handler.Handle(request, default); Assert.NotNull(user); Assert.NotNull(user.FindEvent(typeof(UserRegistered))); uowGeneralMock.Verify(x => x.UserRepository.Create(user), Times.Once); uowGeneralMock.Verify(x => x.SaveChanges(), Times.Once); }
public async Task <RegisterResult> RegisterAsync(string userName, string email, string password) { var passwordHash = BCrypt.Net.BCrypt.HashPassword(password); var userRequest = new CreateUserCommand( username: userName, email: email, pwdHash: passwordHash ); var user = new User(); try { var handler = new CreateUserCommandHandler(_userRepository); userRequest = await handler.HandleAsync(userRequest); user = handler.getUser(); } catch (EntityAlreadyExistsException exc) { //TODO reduce breadth of exception statement return(RegisterResult.GetFailed("Username is already in use")); } await SignInAsync(user); return(RegisterResult.GetSuccess()); }
public async Task Should_ThrowException_When_InputIsNull() { // Arrange var userStore = new Mock <IUserStore <User> >(); userStore.Setup(x => x.FindByIdAsync("123", CancellationToken.None)) .ReturnsAsync(new User() { UserName = "******", Id = 123 }); var roleStore = new Mock <IRoleStore <Role> >(); roleStore.Setup(x => x.FindByIdAsync("123", CancellationToken.None)) .ReturnsAsync(new Role() { Name = "testRole", Id = 123, }); var userManager = new UserManager <User>(userStore.Object, null, null, null, null, null, null, null, null); var roleManager = new RoleManager <Role>(roleStore.Object, null, null, null, null); var commandHandler = new CreateUserCommandHandler(userManager, roleManager); await Assert.ThrowsAsync <InvalidNullInputException>(() => commandHandler.Handle(null, CancellationToken.None)); }
public async Task Handle_GivenUserNotInSystem_ExpectUserToBeAddedAndIdReturned() { var userId = Guid.Empty; var clock = new Mock <IClock>(); var userQueries = new Mock <IUserQueries>(); var userRepository = new Mock <IUserRepository>(); var unitOfWork = new Mock <IUnitOfWork>(); unitOfWork.Setup(x => x.SaveEntitiesAsync(It.IsAny <CancellationToken>())).ReturnsAsync(() => true); userRepository.Setup(x => x.UnitOfWork).Returns(unitOfWork.Object); userRepository.Setup(x => x.Add(It.IsAny <IUser>())).Callback((IUser user) => { userId = user.Id; }); userQueries.Setup(x => x.CheckForPresenceOfUserByEmailAddress(It.IsAny <string>())) .ReturnsAsync(() => new StatusCheckModel(false)); var securitySettings = new Mock <IOptions <SecuritySettings> >(); securitySettings.Setup(x => x.Value).Returns(new SecuritySettings()); var handler = new CreateUserCommandHandler(userRepository.Object, clock.Object, userQueries.Object, securitySettings.Object); var cmd = new CreateUserCommand("email-address", "first-name", "last-name", false, true, new List <Guid>()); var result = await handler.Handle(cmd, CancellationToken.None); userRepository.Verify(x => x.Add(It.IsAny <IUser>()), Times.Once); Assert.Equal(userId, result.Value.UserId); }
public void Context() { _userRepository = MockRepository.GenerateMock<IRepository<User>>(); var handler = new CreateUserCommandHandler(_userRepository); handler.Execute(new CreateUserCommand { EmailAddress = EmailAddress, Password = Password}); }
public async Task Handler_should_throw_email_taken_exception_if_user_already_exists() { //Arrange var fakeUser = new User { Id = Guid.NewGuid().ToString(), Email = "*****@*****.**" }; var fakeUserDbSet = new List <User> { fakeUser }; _userManagerMock.Setup(x => x.FindByEmailAsync(fakeUser.Email)).Returns(Task.FromResult(fakeUser)); var cancellationToken = new CancellationToken(); var command = new CreateUserCommand(fakeUser.Email, "123"); var handler = new CreateUserCommandHandler(_userManagerMock.Object); //Act Task Act() => handler.Handle(command, cancellationToken); //Assert await Assert.ThrowsAsync <UserEmailAddressIsAlreadyTakenException>(Act); }
public void Setup() { repository = Substitute.For <IDbRepository>(); var auditTrailWriter = Substitute.For <IAuditTrailWriter>(); sut = new CreateUserCommandHandler(repository, auditTrailWriter); }
public void Handle_GivenValidRequest_ShouldCreateNewUserAndRaiseUserCreatedNotification() { // Arrange var mediatorMock = new Mock <IMediator>(); var sut = new CreateUserCommandHandler(DbContext, mediatorMock.Object); var command = new CreateUserCommand { FirstName = "Bob", LastName = "Test", EmailAddress = "*****@*****.**", DOB = DateTime.Today.AddYears(-30) }; // Act var result = sut.Handle(command, CancellationToken.None); // Assert mediatorMock.Verify(m => m.Publish(It.Is <UserCreatedNotification>(cc => cc.UserId == result.Result), It.IsAny <CancellationToken>()), Times.Once); result.Result .Should() .NotBeEmpty(); }
public async Task InputDataIsOk_Executed_ReturnUserId() { //Arrange var createUserCommand = new CreateUserCommand { BirthDate = Convert.ToDateTime("15/12/1993"), Email = "*****@*****.**", Name = "Usuário 1", Password = "******", Role = "client" }; var userRepositoryMock = new Mock <IUserRepository>(); var authService = new Mock <IAuthService>(); var createUserCommandHandler = new CreateUserCommandHandler(userRepositoryMock.Object, authService.Object); //Act var id = await createUserCommandHandler.Handle(createUserCommand, new CancellationToken()); //Assert Assert.True(id >= 0); userRepositoryMock.Verify(u => u.AddAsync(It.IsAny <User>()), Times.Once); }
public async Task CreateUserCommand_IdIsEmpty_ShouldThrowArgumentException() { var sut = new CreateUserCommandHandler(_context); await sut.Handle(new CreateUserCommand { Id = Guid.Empty }, CancellationToken.None) .ShouldThrowAsync <ArgumentException>(); }
public async Task CreateOrganizationCommandHandler_ShouldCreateOrganizationAndBindToUser() { var user = Fixture.Build <CreateUserCommand>().Create(); var userHandler = new CreateUserCommandHandler(Context, _mapper); var resultUser = await userHandler.Handle(user); await Context.SaveChangesAsync(); var organization = Fixture.Build <CreateOrganizationCommand>().With(x => x.CreatedBy, resultUser.Id).Create(); var organizationHandler = new CreateOrganizationCommandHandler(Context, _mapper); await organizationHandler.Handle(organization); await Context.SaveChangesAsync(); var createdOrganization = await Context.Organizations.SingleAsync(new FindByIdSpecification <Organization>(organization.Id) .ToExpression()); createdOrganization.Should().NotBeNull(); createdOrganization.CreatedBy.Id.Should().Be(user.Id); var createdUser = await Context.Users.SingleAsync(new FindByIdSpecification <User>(user.Id).ToExpression()); createdUser.Should().NotBeNull(); createdUser.UserOrganizations.Should().HaveCount(1); createdUser.UserOrganizations.First().Organization.Id.Should().Be(organization.Id); createdUser.UserOrganizations.First().User.Id.Should().Be(user.Id); }
public async Task CreateOrganizationCommandValidationTests_ShouldFailedForUsersWhoCreatedOrganizations() { var user = Fixture.Build <CreateUserCommand>().Create(); var userHandler = new CreateUserCommandHandler(Context, _mapper); var resultUser = await userHandler.Handle(user); await Context.SaveChangesAsync(); var organization = Fixture.Build <CreateOrganizationCommand>().With(x => x.CreatedBy, resultUser.Id).Create(); var organizationHandler = new CreateOrganizationCommandHandler(Context, _mapper); await organizationHandler.Handle(organization); await Context.SaveChangesAsync(); var newOrganization = Fixture.Build <CreateOrganizationCommand>().With(x => x.CreatedBy, resultUser.Id).Create(); var validator = new CreateOrganizationCommandValidator(Context); var validationResult = await validator.TestValidateAsync(newOrganization); validationResult.Errors.Should().HaveCount(1); validationResult.ShouldHaveValidationErrorFor(u => u.CreatedBy); }
public CreateUserTest() { // Arrange UserManager = new Mock <MockUserManager>(); Mapper = new Mapper(new MapperConfiguration(cfg => cfg.AddProfile(new MappingProfile()))); Handler = new CreateUserCommandHandler(UserManager.Object, Mapper); }
public async Task GivenRequestContainingExistingEmail_WhenTheUserAlreadyExists_ThrowsExceptionWithBadRequest() { // Arrange, seed an existing user and new command var createUserCommand = new CreateUserCommand { User = new UserRegistrationDto { Username = "******", Email = "*****@*****.**", Password = "******" } }; var existingUserWithSameUsername = new ConduitUser { Email = "*****@*****.**", NormalizedEmail = "*****@*****.**".ToUpperInvariant(), UserName = "******", NormalizedUserName = "******".ToUpperInvariant(), SecurityStamp = "someRandomSecurityStamp" }; existingUserWithSameUsername.PasswordHash = new PasswordHasher <ConduitUser>() .HashPassword(existingUserWithSameUsername, "password"); await UserManager.CreateAsync(existingUserWithSameUsername); // Act var command = new CreateUserCommandHandler(_logger, UserManager, Context, Mapper, TokenService); // Assert await Should.ThrowAsync <ConduitApiException>(async() => { await command.Handle(createUserCommand, CancellationToken.None); }); }
public async Task NullRequestShouldThrowException() { CreateUserCommandHandler handler = CreateHandler(); ArgumentNullException exception = await Assert.ThrowsExceptionAsync <ArgumentNullException>( () => handler.Handle(null, CancellationToken.None)); Assert.AreEqual <string>("request", exception.ParamName); }
public void ThrownInvalidUserServiceException_IfUserDataIsNull_WhenCreateAnUser() { _repository.Setup(x => x.Create(null)).Verifiable(); var _handler = new CreateUserCommandHandler(_repository.Object, _eventBus.Object); Assert.ThrowsAsync <InvalidUserServiceException>( () => _handler.Handle(null) ); }
public async Task ShouldFailIfAttemptingToCreateExistingUser() { var dbContext = InfrastructureFactory.GetInMemoryContext(nameof(ShouldFailIfAttemptingToCreateExistingUser)); var unitOfWork = InfrastructureFactory.GetEfUnitOfWork(dbContext); await unitOfWork.AddAndSaveAsync(EntityFactory.GetUser("johndoe", "Pass@123")); var handler = new CreateUserCommandHandler(unitOfWork, InfrastructureFactory.GetMachineDateTime(), InfrastructureFactory.GetSha1Hasher()); Assert.ThrowsAsync <CreatingExistingUserException>(() => handler.Handle(new CreateUserCommand("johndoe", "Pass@123"), default)); }
public void Context() { _userRepository = A.Fake <IRepository <User> >(); var handler = new CreateUserCommandHandler(_userRepository); handler.ExecuteAsync(new CreateUserCommand { EmailAddress = EmailAddress, Password = Password }).Wait(); }
public async Task DisableOrganizationCommandHandler_ShouldDisableOrganization() { var user = Fixture.Build <CreateUserCommand>().Create(); var userHandler = new CreateUserCommandHandler(Context, _mapper); var resultUser = await userHandler.Handle(user); await Context.SaveChangesAsync(); var organization = Fixture.Build <CreateOrganizationCommand>().With(x => x.CreatedBy, resultUser.Id).Create(); var organizationHandler = new CreateOrganizationCommandHandler(Context, _mapper); await organizationHandler.Handle(organization); await Context.SaveChangesAsync(); var createdOrganization = await Context.Organizations.SingleAsync(new FindByIdSpecification <Organization>(organization.Id) .ToExpression()); createdOrganization.Should().NotBeNull(); createdOrganization.CreatedBy.Id.Should().Be(user.Id); var createdUser = await Context.Users.SingleAsync(new FindByIdSpecification <User>(user.Id).ToExpression()); createdUser.Should().NotBeNull(); createdUser.UserOrganizations.Should().HaveCount(1); createdUser.UserOrganizations.First().Organization.Id.Should().Be(organization.Id); createdUser.UserOrganizations.First().User.Id.Should().Be(user.Id); var disableOrganizationCommand = Fixture.Build <DisableOrganizationCommand>() .With(x => x.Id, createdOrganization.Id) .With(x => x.ModifyBy, createdUser.Id) .Create(); var disableOrganizationCommandHandler = new DisableOrganizationCommandHandler(Context); await disableOrganizationCommandHandler.Handle(disableOrganizationCommand); await Context.SaveChangesAsync(); createdOrganization = await Context.Organizations.SingleOrDefaultAsync(new FindByIdSpecification <Organization>(organization.Id).And(new FindActiveSpecification <Organization>()) .ToExpression()); createdOrganization.Should().BeNull(); createdUser = await Context.Users.SingleAsync(new FindByIdSpecification <User>(user.Id).ToExpression()); createdUser.Should().NotBeNull(); //TODO: Many-to-Many relationships doesn't clear in unit test but correct work in integration test. SO: https://stackoverflow.com/questions/56736652/efcore-unable-to-remove-many-to-many-relation-in-memory-sqlite-but-works-in-pro //createdUser.UserOrganizations.Should().BeEmpty(); }
public async Task CreateAValidUser() { var userCommandMother = UserMother.GetValidCreateUserCommand(); _repository.Setup(x => x.Create(It.IsAny <User>())).Verifiable(); var _handler = new CreateUserCommandHandler(_repository.Object, _eventBus.Object); await _handler.Handle(userCommandMother); _repository.Verify(); }
public async void CreateUserWithoutMailTest() { var command = new CreateUserCommand() { Name = "John", LastName = "Doe", Password = "******" }; var handler = new CreateUserCommandHandler(Context, PasswordHasher); Assert.ThrowsAny <Exception>(() => handler.Handle(command, CancellationToken.None).Result); }
public async void CreateUserWithoutNameTest() { var command = new CreateUserCommand() { LastName = "Doe", Password = "******", Mail = "*****@*****.**" }; var handler = new CreateUserCommandHandler(Context, PasswordHasher); Assert.ThrowsAny <Exception>(() => handler.Handle(command, CancellationToken.None).Result); }
public async Task CreateUserCommand_AfterModelHasBeenValidated_ShouldCreateUserAndReturnUserModel() { var sut = new CreateUserCommandHandler(_context); var userCountBeforeAct = _context.User.ToList().Count; await sut.Handle(new CreateUserCommand { Id = Guid.NewGuid(), Email = _email }, CancellationToken.None); var user = _context.User.FirstOrDefault(e => e.Email == _email); _context.User.ToList().Count.ShouldBe(userCountBeforeAct + 1); user.ShouldBeOfType <Domain.Entities.User>(); }
public async Task ShouldCreateNewUser() { var dbContext = InfrastructureFactory.GetInMemoryContext(nameof(ShouldCreateNewUser)); var unitOfWork = InfrastructureFactory.GetEfUnitOfWork(dbContext); var handler = new CreateUserCommandHandler(unitOfWork, InfrastructureFactory.GetMachineDateTime(), InfrastructureFactory.GetSha1Hasher()); await handler.Handle(new CreateUserCommand("johndoe", "Pass@123"), default); var user = unitOfWork.GetSingleAsync <UserEntity>(u => u.Nickname == "johndoe"); Assert.NotNull(user); }
public void ShouldInvalidWhenPasswordIsNull() { _handler = new CreateUserCommandHandler( _notificationHandlerMock.Object, _eventBusMock.Object, _userManagerMock.Object, _userRepositoryMock.Object); var model = new CreateUserCommandModel(It.IsAny <string>(), null, It.IsAny <string>(), It.IsAny <DateTime>(), It.IsAny <string>()); var handled = _handler.Handle(model).Result; Assert.IsFalse(handled.ExecutionResult == (int)CommandExecutionResponseTypes.SuccessfullyExecution); }
public async Task Handler_should_throw_exception_if_dependency_is_null() { //Arrage //Act void Act() { var command = new CreateUserCommandHandler(null); } //Assert Assert.Throws <ArgumentNullException>(Act); }
public async void CreateUserWithoutLastNameTest() { var command = new CreateUserCommand() { Name = "John", Password = "******", Mail = "*****@*****.**" }; var handler = new CreateUserCommandHandler(Context, PasswordHasher); UserModel user = await handler.Handle(command, CancellationToken.None); Assert.Contains(Users, u => u.Id == user.Id); }
public async Task Handle_ValidCommand_ShouldSaveEntriesSuccessfully(User User) { // Arrange _mapperMock.Setup(m => m.Map <User>(It.IsAny <CreateUserCommand>())) .Returns(User); // AutoMapper setup var sut = new CreateUserCommandHandler(_context, _mapperMock.Object); // creating system under test // Act await sut.Handle(new CreateUserCommand(), CancellationToken.None); // Assert _context.Users.Count().ShouldBe(1); }
public void BeInstantiatedAsync() { // Arrange IRequestHandler <CreateUserCommand, string> handler = new CreateUserCommandHandler(_MockUserManager.Object); var builder = new StringBuilder(); // Act var result = handler.Handle(new CreateUserCommand() { userName = "******" }, default); // Assert result.Equals(false); }
public void CreateUser() { IEnumerable<User> users = new User[] {}; ApplicationDbContext dbContext = new Mock<ApplicationDbContext>("Test") .SetupDbContextData(x => x.Users, users) .Build(); // Act CreateUserCommandHandler commandHandler = new CreateUserCommandHandler(dbContext); commandHandler.Execute(new DataModel.Commands.CreateUserCommand("User1", "User1", "*****@*****.**")); // Assert User[] result = dbContext.Users.ToArray(); Assert.AreEqual(1, result.Count()); Assert.AreEqual(1, result[0].Id); Assert.AreEqual("User1", result[0].FirstName); Assert.AreEqual("User1", result[0].LastName); Assert.AreEqual("*****@*****.**", result[0].Email); Assert.AreEqual(false, result[0].IsActive); }
public void Setup() { repository = Substitute.For<IDbRepository>(); var auditTrailWriter = Substitute.For<IAuditTrailWriter>(); sut = new CreateUserCommandHandler(repository, auditTrailWriter); }
private static async Task CreateUsersAsync(ICommandsDbContext commandsDbContext, IMediator bus) { var usersCount = await commandsDbContext.Users.CountAsync("{}"); if (usersCount > 0) return; var firstNamesIndex = 0; var lastNamesIndex = 0; usersCount = 100; var firstNames = new string[] { "John", "Paul", "Ringo", "Jack", "David", "Jim", "Johnny", "Brad", "Kim", "Jimmy", "Robert", "Freddy", "Matthew", "Nicholas", "Mike" }.OrderBy(n => Guid.NewGuid()).ToArray(); var lastNames = new string[] { "Jones", "Mercury", "Starr", "Page", "Pitt", "Cage", "Bones", "Doe", "Bonham", "White", "Plant", "Portnoy", "Grohl", "May" }.OrderBy(n => Guid.NewGuid()).ToArray(); var commandHandler = new CreateUserCommandHandler(commandsDbContext, bus); var command = new CreateUser(Guid.NewGuid(), "admin", "admin", "*****@*****.**", true); await commandHandler.Handle(command); command = new CreateUser(Guid.NewGuid(), "user", "user", "*****@*****.**"); await commandHandler.Handle(command); for (int i = 0; i < usersCount; i++) { var firstName = firstNames[(firstNamesIndex++) % firstNames.Length]; var lastName = lastNames[(lastNamesIndex++) % lastNames.Length]; var username = string.Format("{0}.{1}", firstName, lastName).ToLower(); var email = string.Format("{0}@email.com", username); if (await FindUserByEmailAsync(commandsDbContext.Users, email)) { var count = 0; while (true) { email = string.Format("{0}{1}@email.com", username, ++count); if (!await FindUserByEmailAsync(commandsDbContext.Users, email)) break; if (count > 1000) { email = string.Empty; break; } } } if (string.IsNullOrWhiteSpace(email)) continue; command = new CreateUser(Guid.NewGuid(), firstName, lastName, email); await commandHandler.Handle(command); } }