Example #1
0
        public void TestCommandHandle()
        {
            var accountName        = "testName";
            var accountServiceMock = new Mock <IAggregateService <AccountAggregate> >();

            accountServiceMock.Setup(m => m.Load(It.IsAny <Guid>())).Returns((Guid guid) => new AccountAggregate());
            var eventPublisherMock = new Mock <IEventPublisher>();

            eventPublisherMock.Setup(m => m.Publish(It.IsAny <CreateAccountEvent>())).Callback((IEvent e) =>
            {
                Assert.IsType <CreateAccountEvent>(e);
                CreateAccountEvent createAccountEvent = (CreateAccountEvent)e;
                Assert.Equal(accountName, createAccountEvent.AccountName);
                Assert.NotEqual(Guid.Empty, createAccountEvent.ItemGuid);
                Assert.Equal(Guid.Empty, createAccountEvent.EventGuid);
            });
            var      commandHandler = new CreateAccountCommandHandler(accountServiceMock.Object, eventPublisherMock.Object);
            ICommand command        = new CreateAccountCommand {
                Name = accountName
            };

            commandHandler.Handle((CreateAccountCommand)command);

            eventPublisherMock.VerifyAll();
        }
Example #2
0
        public void Success()
        {
            var testFixture = new QueryTestFixture();
            var mockFactory = new MockRepository(MockBehavior.Loose);

            var mediator = mockFactory.Create <IMediator>();

            mediator.Setup(s => s.Publish(It.IsAny <CreatedAccountDomainEvent>(), It.IsAny <CancellationToken>()))
            .Returns(Task.Run(() => { }));

            var ct = new CancellationToken();

            var hashService = mockFactory.Create <IHashService>();

            var cmd = new CreateAccountCommandHandler(mediator.Object, testFixture.Context, hashService.Object);

            var cmdArgs = new CreateAccountCommand()
            {
                Alias    = "alias",
                Email    = "*****@*****.**",
                Password = "******"
            };

            Assert.DoesNotThrowAsync(async() => await cmd.Handle(cmdArgs, ct));
        }
Example #3
0
        public void ExistWitTheSameEmail()
        {
            var testFixture = new QueryTestFixture();

            var dbContext   = testFixture.Context;
            var mockFactory = new MockRepository(MockBehavior.Loose);

            dbContext.Add(new Account()
            {
                Email = "*****@*****.**"
            });
            dbContext.SaveChanges();

            var mediator = mockFactory.Create <IMediator>();
            var ct       = new CancellationToken();

            var hashService = mockFactory.Create <IHashService>();

            var cmd = new CreateAccountCommandHandler(mediator.Object, dbContext, hashService.Object);

            var cmdArgs = new CreateAccountCommand()
            {
                Alias    = "alias",
                Email    = "*****@*****.**",
                Password = "******"
            };

            Assert.ThrowsAsync <UnableCreateAccountException>(async() => await cmd.Handle(cmdArgs, ct));
        }
Example #4
0
        public async Task CreateAccountCommand_DoesNot_create_account_when_Income_threshold_is_not_met()
        {
            //Arrange
            var userId  = Guid.NewGuid();
            var request = new CreateAccountRequest {
                UserId = userId
            };
            var response = new CreateAccountResponse();

            using (var db = MockDbContext())
            {
                db.Users.RemoveRange(db.Users);
                db.SaveChanges();

                db.Users.Add(new User {
                    Id = userId, Name = "Tester1", Email = "*****@*****.**", Salary = 2000, Expenses = 1500
                });
                db.SaveChanges();

                var command = new CreateAccountCommand(request);
                var handler = new CreateAccountCommandHandler(db);

                //Act
                response = await handler.Handle(command, CancellationToken.None);
            }

            //Assert
            response.Status.Should().Contain("Income");
            response.Id.Should().BeEmpty();
        }
Example #5
0
        public async Task CreateAccountCommand_DoesNot_create_account_when_User_notfound()
        {
            //Arrange
            var userId  = Guid.NewGuid();
            var request = new CreateAccountRequest {
                UserId = userId
            };
            var response = new CreateAccountResponse();

            using (var db = MockDbContext())
            {
                db.Users.RemoveRange(db.Users);
                db.SaveChanges();

                var command = new CreateAccountCommand(request);
                var handler = new CreateAccountCommandHandler(db);

                //Act
                response = await handler.Handle(command, CancellationToken.None);
            }

            //Assert
            response.Status.Should().Contain("not be created");
            response.Id.Should().BeEmpty();
        }
Example #6
0
        public async Task ThenTheAccountIsCreated()
        {
            var accountId = 123443;
            var name      = "Account Name";

            await _handler.Handle(new CreateAccountCommand(accountId, name));

            _accountRepository.Verify(x => x.CreateAccount(accountId, name));
        }
        public void When_create_account_command_is_triggered_with_an_empty_name_it_should_throw()
        {
            // Arrange
            var eventStore = new InMemoryEventRepositoryBuilder().Build();
            var handler = new CreateAccountCommandHandler(eventStore);

            // Act
            Action action = () => handler.Handle(new CreateAccountCommand(Guid.NewGuid(), ""));

            // Assert
            action.ShouldThrow<ArgumentException>();
        }
Example #8
0
        public async Task ThenIfThereAreMoreThanOneEmprefPassedThenTheyAreAddedToTheAccount()
        {
            //Arrange
            var createAccountCommand = new CreateAccountCommand {
                PayeReference = "123/abc,456/123", AccessToken = "123rd", RefreshToken = "45YT", OrganisationStatus = "active"
            };

            //Act
            await _handler.Handle(createAccountCommand);

            //Assert
            _accountRepository.Verify(x => x.CreateAccount(It.IsAny <long>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime?>(), "123/abc", "123rd", "45YT", "active", It.IsAny <string>(), It.IsAny <short>(), It.IsAny <short?>(), It.IsAny <string>()), Times.Once);
            _accountRepository.Verify(x => x.AddPayeToAccount(It.Is <Paye>(c => c.AccountId.Equals(ExpectedAccountId) && c.EmpRef.Equals("456/123") && c.AccessToken.Equals("123rd") && c.RefreshToken.Equals("45YT"))), Times.Once);
        }
Example #9
0
        public async Task ThenTheAccountDataIsRetrievedAndSaved()
        {
            var expectedAccount = new AccountDetailViewModelBuilder().Build();
            var accountHref     = $"/api/accounts/{expectedAccount.HashedAccountId}";

            _accountGateway.Setup(x => x.GetAccount(accountHref)).ReturnsAsync(expectedAccount);

            await _commandHandler.Handle(new CreateAccountCommand { AccountHref = accountHref });

            _accountRepository.Verify(x => x.SaveAccount(expectedAccount), Times.Once);
            _mediator.Verify(x => x.PublishAsync(It.Is <CreateLegalEntityCommand>(c => c.LegalEntityHref == expectedAccount.LegalEntities[0].Href)), Times.Once);
            _mediator.Verify(x => x.PublishAsync(It.Is <CreatePayeSchemeCommand>(c => c.PayeSchemeHref == expectedAccount.PayeSchemes[0].Href)), Times.Once);
        }
        public void When_create_account_command_is_triggered_it_should_raise_the_appropriate_events()
        {
            // Arrange
            var eventStore = new InMemoryEventRepositoryBuilder().Build();
            var handler = new CreateAccountCommandHandler(eventStore);

            // Act
            handler.Handle(new CreateAccountCommand(Guid.NewGuid(), "Thomas"));

            // Assert
            eventStore.Events.Should().HaveCount(1);
            eventStore.Events.OfType<AccountCreatedEvent>().Should().HaveCount(1);
        }
Example #11
0
        public async Task CreateAccountCommandHandler_Handle_AccountAlreadyExistsFail()
        {
            var options = new DbContextOptionsBuilder <AccountsContext>()
                          .UseInMemoryDatabase(nameof(CreateAccountCommandHandler_Handle_AccountAlreadyExistsFail))
                          .Options;

            var accountContext = new AccountsContext(options);

            var accountRepository = new AccountRepository(accountContext);

            var createAccountCommandHandler = new CreateAccountCommandHandler(accountRepository);

            await createAccountCommandHandler
            .Handle(new CreateAccountCommand("test", "password"), CancellationToken.None)
            .ConfigureAwait(false);

            await Assert.ThrowsAsync <InvalidOperationException>(async() =>
            {
                await createAccountCommandHandler
                .Handle(new CreateAccountCommand("test", "password"), CancellationToken.None)
                .ConfigureAwait(false);
            });
        }
        public async void Handle_GivenValidCustomer_ShouldCreateAccount()
        {
            // Arrange

            // Create Customer
            var customerCreation          = new CreateCustomerCommandHandler(_customerLogger, _mapper, _customerRepository);
            var newCustomerCommandRequest = new CreateCustomerCommand {
                Email = "*****@*****.**", MonthlyIncome = 20000, MonthlyExpense = 200
            };
            var customerCreationResult = await customerCreation.Handle(newCustomerCommandRequest, CancellationToken.None);

            var newAccountCommandRequest = new CreateAccountCommand {
                Email = customerCreationResult.Email, customerId = customerCreationResult.Id
            };

            // Act
            var accountCreationSUT = new CreateAccountCommandHandler(_accountLogger, _mapper, _accountRepository, _customerRepository);

            var accountCreationResult = await accountCreationSUT.Handle(newAccountCommandRequest, CancellationToken.None);

            var customerFromDb = _customerDbContext.Customers.Find(customerCreationResult.Id);
            var accountFromDb  = _customerDbContext.Accounts.Find(accountCreationResult.AccountNo);

            // Assert
            Assert.NotNull(customerCreationResult);
            Assert.IsType <Guid>(customerCreationResult.Id);
            Assert.Equal(newCustomerCommandRequest.Email, customerCreationResult.Email);
            Assert.Equal(newCustomerCommandRequest.MonthlyExpense, customerCreationResult.MonthlyExpense);
            Assert.Equal(newCustomerCommandRequest.MonthlyIncome, customerCreationResult.MonthlyIncome);

            Assert.NotNull(customerFromDb);
            Assert.Equal(customerCreationResult.Id, customerFromDb.Id);
            Assert.Equal(newCustomerCommandRequest.Email, customerFromDb.Email);
            Assert.Equal(newCustomerCommandRequest.MonthlyExpense, customerFromDb.MonthlyExpense);
            Assert.Equal(newCustomerCommandRequest.MonthlyIncome, customerFromDb.MonthlyIncome);


            Assert.NotNull(accountCreationResult);
            Assert.Equal(customerCreationResult.Id, accountCreationResult.customerId);
            Assert.Equal(customerCreationResult.Email, accountCreationResult.Email);
            Assert.True(accountFromDb.Active);

            Assert.NotNull(accountFromDb);
            Assert.Equal(accountCreationResult.customerId, accountFromDb.CustomerId);
            Assert.Equal(accountCreationResult.Email, accountFromDb.Email);
        }
Example #13
0
        public async Task CreateAccountCommandHandler_Handle_AccountCreated()
        {
            var options = new DbContextOptionsBuilder <AccountsContext>()
                          .UseInMemoryDatabase(nameof(CreateAccountCommandHandler_Handle_AccountCreated))
                          .Options;

            var accountContext = new AccountsContext(options);

            var accountRepository = new AccountRepository(accountContext);

            var createAccountCommandHandler = new CreateAccountCommandHandler(accountRepository);

            var accountId = await createAccountCommandHandler
                            .Handle(new CreateAccountCommand("test", "password"), CancellationToken.None)
                            .ConfigureAwait(false);

            Assert.True(Guid.TryParse(accountId.ToString(), out var unused));
        }
Example #14
0
        public async Task CreateAccountSuccessfuly()
        {
            // Arrange
            handler      = new CreateAccountCommandHandler(_Database);
            accountModel = new CreateAccountCommand()
            {
                AccountId      = "0000",
                AccountName    = "Cash",
                Active         = 0,
                CatagoryId     = 1,
                OpeningBalance = 100,
                CostCenterId   = 1
            };

            // Act
            var response = await handler.Handle(accountModel, CancellationToken.None);

            // Assert
            Assert.NotEqual(0, response);
        }
Example #15
0
        public async Task CreateNewAccount()
        {
            var handler = new CreateAccountCommandHandler(DbContext);
            var request = new CreateAccountCommand
            {
                Email                = "*****@*****.**",
                Password             = "******",
                PasswordConfirmation = "AUDd9d722h(H!U&(H!wbu13g"
            };

            var result = await handler.Handle(request, CancellationToken.None);

            Assert.True(result is UserDto);
            Assert.Equal("*****@*****.**", result.Email);

            var createdEntry = await DbContext
                               .Set <User>()
                               .Where(u => u.Uid == result.Id)
                               .FirstAsync();

            Assert.NotNull(createdEntry);
            Assert.True(BCrypt.Net.BCrypt.Verify("AUDd9d722h(H!U&(H!wbu13g", createdEntry.EncryptedPassword));
        }
        public async void Handle_GivenCustomerNotExist_ShouldThrowNotFoundException()
        {
            // Arrange

            // Create Customer

            var notCustomerEmail = "*****@*****.**";

            var newAccountCommandRequest = new CreateAccountCommand {
                Email = notCustomerEmail, customerId = Guid.NewGuid()
            };

            // Act
            var accountCreationSUT = new CreateAccountCommandHandler(_accountLogger, _mapper, _accountRepository, _customerRepository);

            var accountCreationExceptionResult = await Assert.ThrowsAsync <NotFoundException>(async() => await accountCreationSUT.Handle(newAccountCommandRequest, CancellationToken.None));

            var accountFromDb = _accountRepository.GetAccountByEmail(notCustomerEmail);

            // Assert
            Assert.Null(accountFromDb);
        }
Example #17
0
        public async Task ThenTheIdHashingServiceIsCalledAfterTheAccountIsCreated()
        {
            //Arrange
            var createAccountCommand = new CreateAccountCommand {
                PayeReference = "123/abc,456/123", AccessToken = "123rd", RefreshToken = "45YT", ExternalUserId = _user.Ref.ToString()
            };

            //Act
            await _handler.Handle(createAccountCommand);

            //Assert
            _hashingService.Verify(x => x.HashValue(ExpectedAccountId), Times.Once);
        }
        public async void Handle_GivenCustomerWithInSufficientBalance_ShouldThrowBadRequest()
        {
            // Arrange

            // Create Customer
            var customerCreation          = new CreateCustomerCommandHandler(_customerLogger, _mapper, _customerRepository);
            var newCustomerCommandRequest = new CreateCustomerCommand {
                Email = "*****@*****.**", MonthlyIncome = 2000, MonthlyExpense = 1200
            };
            var customerCreationResult = await customerCreation.Handle(newCustomerCommandRequest, CancellationToken.None);

            var newAccountCommandRequest = new CreateAccountCommand {
                Email = customerCreationResult.Email, customerId = customerCreationResult.Id
            };

            // Act
            var accountCreationSUT = new CreateAccountCommandHandler(_accountLogger, _mapper, _accountRepository, _customerRepository);

            var accountCreationExceptionResult = await Assert.ThrowsAsync <BadRequestException>(async() => await accountCreationSUT.Handle(newAccountCommandRequest, CancellationToken.None));

            var accountFromDb = _accountRepository.GetAccountByEmail(customerCreationResult.Email);

            // Assert
            Assert.Null(accountFromDb);
        }