Пример #1
0
        public static void Main(string[] args)
        {
            var bus = BusSetup.StartWith <Conservative>()
                      .Apply <FlexibleSubscribeAdapter>(a =>
            {
                a.ByInterface(typeof(IEventHandler <>));
                a.ByInterface(typeof(ICommandHandler <>));
            }).Construct();

            var someAwesomeUi = new SomeAwesomeUi(bus);

            using (store = WireupEventStore(bus))
            {
                var repository = new EventStoreRepository(store, new AggregateFactory(), new ConflictDetector());

                var handler  = new CreateAccountCommandHandler(repository);
                var handler2 = new CloseAccountCommandHandler(repository);
                bus.Subscribe(handler);
                bus.Subscribe(handler2);
                bus.Subscribe(new KaChingNotifier());
                bus.Subscribe(new OmgSadnessNotifier());

                someAwesomeUi.CreateNewAccount(AggregateId, "Luiz", "@luizdamim");
                someAwesomeUi.CloseAccount(AggregateId);
            }

            Console.ReadLine();
        }
Пример #2
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));
        }
Пример #3
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();
        }
Пример #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();
        }
Пример #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();
        }
Пример #6
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));
        }
        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);
        }
Пример #8
0
        public void Arrange()
        {
            _accountRepository = new Mock <IAccountRepository>();
            _accountGateway    = new Mock <IAccountGateway>();
            _mediator          = new Mock <IMediator>();

            _commandHandler = new CreateAccountCommandHandler(_accountRepository.Object, _accountGateway.Object, _mediator.Object);
        }
Пример #9
0
        public void Arrange()
        {
            _accountRepository = new Mock <IAccountRepository>();

            _logger = new Mock <ILog>();

            _handler = new CreateAccountCommandHandler(_accountRepository.Object, _logger.Object);
        }
Пример #10
0
        public void TestCanHandleFalse()
        {
            var      accountServiceMock = new Mock <IAggregateService <AccountAggregate> >();
            var      eventPublisherMock = new Mock <IEventPublisher>();
            var      commandHandler     = new CreateAccountCommandHandler(accountServiceMock.Object, eventPublisherMock.Object);
            ICommand command            = new Mock <ICommand>().Object;

            var canHandle = commandHandler.CanHandle(command);

            Assert.False(canHandle);
        }
        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>();
        }
        public static void ClassInitialise(TestContext context)
        {
            bus = new InProcessBus(DispatchStrategy.Synchronous);

            client = new SomeAwesomeUi(bus);

            store = Wireup.Init().UsingInMemoryPersistence().Build();
            var repository = new EventStoreRepository(store, new AggregateFactory(), new ConflictDetector());
            var handler    = new CreateAccountCommandHandler(repository);

            bus.Subscribe(handler);
            accountId = client.CreateNewAccount();
        }
        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);
        }
Пример #14
0
        public void TestCanHandle()
        {
            var      accountServiceMock = new Mock <IAggregateService <AccountAggregate> >();
            var      eventPublisherMock = new Mock <IEventPublisher>();
            var      commandHandler     = new CreateAccountCommandHandler(accountServiceMock.Object, eventPublisherMock.Object);
            var      accountName        = "testName";
            ICommand command            = new CreateAccountCommand {
                Name = accountName
            };

            var canHandle = commandHandler.CanHandle(command);

            Assert.True(canHandle);
        }
        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);
        }
Пример #16
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));
        }
        // Here, I'm wiring up my MemBus instance and telling it how to resolve my subscribers
        // MemBus also has an awesome way to resolve subscribers from an IoC container. In prod,
        // I'll wire my subscribers into StructureMap and have MemBus resolve them from there.
        // I'm also initializing my awesome test client UI which, if you'll recall from way back at the start
        // simply publishes commands to my MemBus instance (and, again, it could be whatever)
        public SynchronousDispatchTests()
        {
            this.bus = new InProcessBus(DispatchStrategy.Synchronous);

      #pragma warning disable 0618
            this.store = Wireup.Init()
                         .UsingInMemoryPersistence()
                         .UsingSynchronousDispatchScheduler()
                         .DispatchTo(new DelegateMessageDispatcher(c => MassTransitDispatcher.DispatchCommit(this.bus, c)))
                         .Build();
      #pragma warning restore 0618

            this.repository = new EventStoreRepository(this.store, new AggregateFactory(), new ConflictDetector());
            var handler = new CreateAccountCommandHandler(this.repository);

            this.bus.Subscribe(handler);

            this.client = new SomeAwesomeUi(this.bus);
        }
Пример #18
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);
        }
        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);
        }
Пример #20
0
        public void Arrange()
        {
            _accountRepository = new Mock <IAccountRepository>();
            _accountRepository.Setup(x => x.GetPayeSchemesByAccountId(ExpectedAccountId)).ReturnsAsync(new List <PayeView> {
                new PayeView {
                    LegalEntityId = ExpectedLegalEntityId
                }
            });
            _accountRepository.Setup(x => x.CreateAccount(It.IsAny <long>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime?>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <short>(), It.IsAny <short?>(), It.IsAny <string>())).ReturnsAsync(new CreateAccountResult {
                AccountId = ExpectedAccountId, LegalEntityId = 0L, EmployerAgreementId = 0L
            });

            _userRepository = new Mock <IUserRepository>();
            _userRepository.Setup(x => x.GetByUserRef(It.IsAny <string>())).ReturnsAsync(new User());

            _messagePublisher = new Mock <IMessagePublisher>();
            _mediator         = new Mock <IMediator>();
            _validator        = new Mock <IValidator <CreateAccountCommand> >();
            _validator.Setup(x => x.ValidateAsync(It.IsAny <CreateAccountCommand>())).ReturnsAsync(new ValidationResult {
                ValidationDictionary = new Dictionary <string, string>()
            });

            _hashingService = new Mock <IHashingService>();
            _hashingService.Setup(x => x.HashValue(ExpectedAccountId)).Returns(ExpectedHashString);

            _genericEventFactory = new Mock <IGenericEventFactory>();
            _accountEventFactory = new Mock <IAccountEventFactory>();

            _handler = new CreateAccountCommandHandler(
                _accountRepository.Object,
                _userRepository.Object,
                _messagePublisher.Object,
                _mediator.Object,
                _validator.Object,
                _hashingService.Object,
                _genericEventFactory.Object,
                _accountEventFactory.Object);
        }
Пример #21
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);
            });
        }
Пример #22
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));
        }
Пример #23
0
        public void Arrange()
        {
            _accountRepository = new Mock <IAccountRepository>();
            _accountRepository.Setup(x => x.GetPayeSchemesByAccountId(ExpectedAccountId)).ReturnsAsync(new List <PayeView> {
                new PayeView {
                    LegalEntityId = ExpectedLegalEntityId
                }
            });
            _accountRepository.Setup(x => x.CreateAccount(It.IsAny <CreateAccountParams>())).ReturnsAsync(new CreateAccountResult {
                AccountId = ExpectedAccountId, LegalEntityId = ExpectedLegalEntityId, EmployerAgreementId = ExpectedEmployerAgreementId, AccountLegalEntityId = ExpectedAccountLegalEntityId
            });

            _eventPublisher = new TestableEventPublisher();
            _mediator       = new Mock <IMediator>();

            _user = new User {
                Id = 33, FirstName = "Bob", LastName = "Green", Ref = Guid.NewGuid()
            };

            _mediator.Setup(x => x.SendAsync(It.IsAny <GetUserByRefQuery>()))
            .ReturnsAsync(new GetUserByRefResponse {
                User = _user
            });

            _validator = new Mock <IValidator <CreateAccountCommand> >();
            _validator.Setup(x => x.ValidateAsync(It.IsAny <CreateAccountCommand>())).ReturnsAsync(new ValidationResult {
                ValidationDictionary = new Dictionary <string, string>()
            });

            _hashingService = new Mock <IHashingService>();
            _hashingService.Setup(x => x.HashValue(ExpectedAccountId)).Returns(ExpectedHashString);

            _externalhashingService = new Mock <IPublicHashingService>();
            _externalhashingService.Setup(x => x.HashValue(ExpectedAccountId)).Returns(ExpectedPublicHashString);

            _accountLegalEntityHashingService = new Mock <IAccountLegalEntityPublicHashingService>();
            _accountLegalEntityHashingService.Setup(x => x.HashValue(ExpectedAccountLegalEntityId)).Returns(ExpectedAccountLegalEntityPublicHashString);

            _genericEventFactory = new Mock <IGenericEventFactory>();
            _accountEventFactory = new Mock <IAccountEventFactory>();

            _mockAuthorizationService = new Mock <IAuthorizationService>();
            _mockAuthorizationService.Setup(x => x.IsAuthorized("EmployerFeature.ExpressionOfInterest")).Returns(false);

            _mockMembershipRepository = new Mock <IMembershipRepository>();
            _mockMembershipRepository.Setup(r => r.GetCaller(It.IsAny <long>(), It.IsAny <string>()))
            .Returns(Task.FromResult(new MembershipView()
            {
                FirstName = _user.FirstName, LastName = _user.LastName
            }));

            _mockEmployerAgreementRepository = new Mock <IEmployerAgreementRepository>();

            _handler = new CreateAccountCommandHandler(
                _accountRepository.Object,
                _mediator.Object,
                _validator.Object,
                _hashingService.Object,
                _externalhashingService.Object,
                _accountLegalEntityHashingService.Object,
                _genericEventFactory.Object,
                _accountEventFactory.Object,
                _mockMembershipRepository.Object,
                _mockEmployerAgreementRepository.Object,
                _eventPublisher,
                _mockAuthorizationService.Object);
        }