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)); }
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 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(); }
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(); }
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); }
public AccountController(INotifications notifications, IUnitOfWork unitOfWork, CreateAccountCommand command, IUsersRepository usersRepository) : base(notifications, unitOfWork) { _command = command; _usersRepository = usersRepository; }
public async Task <AccountResponse> CreateAccountAsync(CreateAccountCommand createAccountCommand) { if (createAccountCommand == null) { throw new RequestNullException(); } AccountResponse accountResponse; bool alreadyExist = _dataContext.AccountModels.Any(m => m.Email == createAccountCommand.Email); if (alreadyExist) { throw new EmailAlreadyRegisteredException(createAccountCommand.Email); } await using (IDbContextTransaction transaction = _dataContext.Database.BeginTransaction(_integrationEventPublisher, autoCommit: true)) { var accountModel = new AccountModel(createAccountCommand.Email, createAccountCommand.FirstName, createAccountCommand.LastName); await _dataContext.AccountModels.AddAsync(accountModel); await _dataContext.SaveChangesAsync(); accountResponse = accountModel.ToAccountResponse(); var accountCreatedEvent = new AccountCreatedEvent(accountResponse); await _integrationEventPublisher.Publish(accountCreatedEvent); } return(accountResponse); }
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(); }
public AccountTableModel(int id, CreateAccountCommand command) { this.id = id; this.email = command.Email; this.password = command.Password; //this.status = Enum.Parse<AccountStatus>(command.Status); }
public async Task <ActionResult> CreateAccount([FromBody] CreateAccountBody credentials, CancellationToken cancellationToken = default) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserNameOrEmailExistsQuery existsQuery = _mapper.Map <CreateAccountBody, UserNameOrEmailExistsQuery>(credentials); bool exists = await _mediator.Send(existsQuery, cancellationToken); if (exists) { return(StatusCode(StatusCodes.Status403Forbidden, new ErrorResource { StatusCode = StatusCodes.Status403Forbidden, Message = "A user with the same user name or email already exists. Please use different credentials for creating an account" })); } CreateAccountCommand registerCommand = _mapper.Map <CreateAccountBody, CreateAccountCommand>(credentials); int userId = await _mediator.Send(registerCommand, cancellationToken); return(CreatedAtAction(nameof(GetUserProfile), new { userId }, null)); }
public IActionResult Register(CreateAccountCommand account) { if (ModelState.IsValid) { account.Role = "Client"; var result = _identityService.CreateAccount(account).Result.Status; if (result == "Success") { var newAccount = new app.service.Accounts.Commands.CreateAccount.CreateAccountCommand { FirstName = account.FirstName, LastName = account.LastName, EmailAddress = account.Email }; _accountService.CreateAccount(newAccount); return(RedirectToAction("EmailConfirmation")); } else { account.ErrorMessage = result; return(View(account)); } } return(View()); }
public IActionResult Post(CreateAccountCommand command) { var account = mapper.Map <Account>(command); if (!accountRepository.Exists(account)) { try { accountRepository.Add(account); return(StatusCode(201, new { Message = "Account successfully created." })); } catch (FormatException e) { return(StatusCode(400, e.Message)); } catch (Exception e) { return(StatusCode(500, e.Message)); } } else { return(StatusCode(409, new { Message = "The account already exists for this member." })); } }
public async Task WillCallRepositoryToCreateNewAccount() { const int accountId = 23; var cmd = new CreateAccountCommand { ExternalUserId = _user.Ref.ToString(), OrganisationReferenceNumber = "QWERTY", OrganisationName = "Qwerty Corp", OrganisationAddress = "Innovation Centre, Coventry, CV1 2TT", OrganisationDateOfInception = DateTime.Today.AddDays(-1000), Sector = "Sector", PayeReference = "120/QWERTY", AccessToken = Guid.NewGuid().ToString(), RefreshToken = Guid.NewGuid().ToString(), OrganisationStatus = "active", EmployerRefName = "Paye Scheme 1" }; _accountRepository.Setup(x => x.CreateAccount(_user.Id, cmd.OrganisationReferenceNumber, cmd.OrganisationName, cmd.OrganisationAddress, cmd.OrganisationDateOfInception, cmd.PayeReference, cmd.AccessToken, cmd.RefreshToken, cmd.OrganisationStatus, cmd.EmployerRefName, (short)cmd.OrganisationType, cmd.PublicSectorDataSource, cmd.Sector)).ReturnsAsync(new CreateAccountResult { AccountId = accountId, LegalEntityId = 0L, EmployerAgreementId = 0L }); var expectedHashedAccountId = "DJRR4359"; _hashingService.Setup(x => x.HashValue(accountId)).Returns(expectedHashedAccountId); var expectedPublicHashedAccountId = "SCUFF"; _externalhashingService.Setup(x => x.HashValue(accountId)).Returns(expectedPublicHashedAccountId); await _handler.Handle(cmd); _accountRepository.Verify(x => x.CreateAccount(_user.Id, cmd.OrganisationReferenceNumber, cmd.OrganisationName, cmd.OrganisationAddress, cmd.OrganisationDateOfInception, cmd.PayeReference, cmd.AccessToken, cmd.RefreshToken, cmd.OrganisationStatus, cmd.EmployerRefName, (short)cmd.OrganisationType, cmd.PublicSectorDataSource, cmd.Sector)); }
public async Task ThenAAddedLegalEntityEventIsPublished(OrganisationType inputOrganisationType, Types.Models.OrganisationType expectedOrganisationType) { const string organisationName = "Org"; //Arrange var createAccountCommand = new CreateAccountCommand { PayeReference = "123EDC", AccessToken = "123rd", RefreshToken = "45YT", OrganisationStatus = "active", OrganisationName = organisationName, ExternalUserId = _user.Ref.ToString(), OrganisationType = inputOrganisationType, OrganisationReferenceNumber = ExpectedOrganisationReferenceNumber, OrganisationAddress = ExpectedOrganisationAddress }; //Act await _handler.Handle(createAccountCommand); //Assert var addedLegalEntityEvent = _eventPublisher.Events.OfType <AddedLegalEntityEvent>().Single(); addedLegalEntityEvent.AgreementId.Should().Be(ExpectedEmployerAgreementId); addedLegalEntityEvent.LegalEntityId.Should().Be(ExpectedLegalEntityId); addedLegalEntityEvent.OrganisationName.Should().Be(organisationName); addedLegalEntityEvent.AccountId.Should().Be(ExpectedAccountId); addedLegalEntityEvent.AccountLegalEntityId.Should().Be(ExpectedAccountLegalEntityId); addedLegalEntityEvent.AccountLegalEntityPublicHashedId.Should().Be(ExpectedAccountLegalEntityPublicHashString); addedLegalEntityEvent.UserName.Should().Be(_user.FullName); addedLegalEntityEvent.UserRef.Should().Be(_user.Ref); addedLegalEntityEvent.OrganisationReferenceNumber.Should().Be(ExpectedOrganisationReferenceNumber); addedLegalEntityEvent.OrganisationAddress.Should().Be(ExpectedOrganisationAddress); addedLegalEntityEvent.OrganisationType.Should().Be(expectedOrganisationType); //addedLegalEntityEvent.Created.Should().Be(rightAboutNow); }
public async Task B_CreateUserAndAccount_SalaryExpensesNotGreaterThan100_Return400StatusCode() { //Arrange CreateUserCommand createUserCommand = new CreateUserCommand { Email = "*****@*****.**", FirstName = "Paul", LastName = "Walker", Expenses = 300, Salary = 500 }; CreateAccountCommand createAccountCommand = new CreateAccountCommand { Balance = 1000, Type = "ZipPay" }; // Act var userContent = TestHelpers.CreateHttpContent(createUserCommand); var userResponse = await TestHelpers.MakePostRequest(client, "/api/v1/users", userContent); var userResponseObject = await TestHelpers.DeserializeResponse <CreateUserResponse>(userResponse); createAccountCommand.UserId = userResponseObject.UserId; var accountContent = TestHelpers.CreateHttpContent(createAccountCommand); var accountResponse = await TestHelpers.MakePostRequest(client, "/api/v1/accounts", accountContent); var accountResponseObject = await accountResponse.Content.ReadAsStringAsync(); //Assert Assert.Equal(HttpStatusCode.BadRequest, accountResponse.StatusCode); Assert.Contains("The difference between salary and expenses should be more than $1000", accountResponseObject); }
public async Task <IActionResult> CreateAccount([FromBody] AccountRequest account) { var command = new CreateAccountCommand(_mapper.Map <Account>(account), account.Password); var result = await _bus.Send(command); return(Created("", _mapper.Map <AccountResponse>(result))); }
public async Task CreateAccountAsync(CreateAccountCommand command) { var account = BuildAccountFromDomainEvents(command.AccountNumber); var events = account.CreateAccount(command); await this.EventStore.AddEventsAsync(events); }
static void Main(string[] args) { var runtime = new SampleRunTime(); runtime.Start(); var fakeAccountTable = new FakeAccountTable(); runtime.ServiceLocator.Register(fakeAccountTable); runtime.ServiceLocator.Register(new AccountReportReadService(fakeAccountTable)); var commandBus = runtime.ServiceLocator.Resolve <ICommandBus>(); var cmd = new CreateAccountCommand { FirstName = "Ali", LastName = "Kh" }; commandBus.Send(cmd); var accountReportReadModel = runtime.ServiceLocator.Resolve <AccountReportReadService>(); Console.WriteLine("Accounts in database"); Console.WriteLine("####################"); foreach (var account in accountReportReadModel.GetAccounts()) { Console.WriteLine("Id: {0} Name: {1}", account.Id, account.Name); } runtime.Shutdown(); Console.ReadLine(); }
public void ExecuteReturnsSuccessWhenGood(string tName, string tPassword, string tEmail) { var vHashProvider = new Mock<IHashProvider>(); var vDocumentStore = GetEmbeddedDatabase; var vAccountCommandFactory = new Mock<IAccountCommandFactory>(); var vSendConfirmationCommand = new Mock<ISendConfirmationCommand>(); vAccountCommandFactory .Setup(t => t.CreateSendConfirmationCommand(It.IsAny<Account>())) .Returns(vSendConfirmationCommand.Object); vSendConfirmationCommand.Setup(t => t.Execute()).Returns(true); var vCreateAccount = new CreateAccount { Name = tName, Password = tPassword, Email = tEmail }; var vRandomProvider = new Mock<IRandomProvider>(); var vCreateAccountCommand = new CreateAccountCommand(vDocumentStore, vHashProvider.Object, vAccountCommandFactory.Object, vRandomProvider.Object, vCreateAccount); var vResult = vCreateAccountCommand.Execute(); Assert.AreEqual(eAccountCreationStatus.Success, vResult); }
public async Task RunBankingScenario() { var accountId = Guid.NewGuid(); var repo = await ProviderFactory.Current.CreateRepositoryAsync() .ConfigureAwait(false); var handler = new BankAccountCommandHandlers(repo); const string joeBloggs = "Joe Bloggs"; await handler.Handle(CreateAccountCommand.Create(Guid.NewGuid(), accountId, joeBloggs)).ConfigureAwait(false); await handler.Handle(DepositFundsCommand.Create(Guid.NewGuid(), accountId, 10)).ConfigureAwait(false); await handler.Handle(DepositFundsCommand.Create(Guid.NewGuid(), accountId, 35)).ConfigureAwait(false); await handler.Handle(WithdrawFundsCommand.Create(Guid.NewGuid(), accountId, 25)).ConfigureAwait(false); await handler.Handle(DepositFundsCommand.Create(Guid.NewGuid(), accountId, 5)).ConfigureAwait(false); await handler.Handle(WithdrawFundsCommand.Create(Guid.NewGuid(), accountId, 10)).ConfigureAwait(false); var actual = await repo.GetByIdAsync <BankAccount>(accountId).ConfigureAwait(false); actual.Id.Should().Be(accountId); actual.Name.Should().Be(joeBloggs); actual.CurrentBalance.Should().Be(15); actual.Transactions.Count.Should().Be(5); }
public async Task ThenIfTheCommandIsValidTheCreateAuditCommandIsCalledForEachComponent() { //Arrange var createAccountCommand = new CreateAccountCommand { PayeReference = "123/abc,456/123", AccessToken = "123rd", RefreshToken = "45YT", OrganisationType = OrganisationType.CompaniesHouse, OrganisationName = "OrgName", EmployerRefName = "123AB", ExternalUserId = _user.Ref.ToString(), OrganisationAddress = "Address", OrganisationDateOfInception = new DateTime(2017, 01, 30), OrganisationReferenceNumber = "TYG56", OrganisationStatus = "Active", PublicSectorDataSource = 2, Sector = "Sector" }; //Act await _handler.Handle(createAccountCommand); //Assert _mediator.Verify( x => x.SendAsync(It.Is <CreateAuditCommand>(c => c.EasAuditMessage.ChangedProperties.SingleOrDefault(y => y.PropertyName.Equals("AccountId") && y.NewValue.Equals(ExpectedAccountId.ToString())) != null && c.EasAuditMessage.ChangedProperties.SingleOrDefault(y => y.PropertyName.Equals("AccountId") && y.NewValue.Equals(ExpectedAccountId.ToString())) != null ))); }
public void Bootstrap() { IEventStoreConnection esConnection = EventStoreConnection.Create("ConnectTo=tcp://admin:changeit@localhost:1113"); conn = new EventStoreConnectionWrapper(esConnection); esConnection.Connected += (_, __) => Console.WriteLine("Connected"); esConnection.ConnectAsync().Wait(); IStreamNameBuilder namer = new PrefixedCamelCaseStreamNameBuilder(); IEventSerializer ser = new JsonMessageSerializer(); repo = new StreamStoreRepository(namer, conn, ser); cmdHandler = new AccountCommandHandler(repo); AccountAggregate acct = null; try { var command = new CreateAccountCommand() { AccountId = _accountId, HolderName = _holderName }; cmdHandler.Handle(command); } catch (Exception e) { } listener = new StreamListener("AccountAggregate", conn, namer, ser); _readModel = new BalanceReadModel(() => listener); }
public ICommandResult Handle(CreateAccountCommand command) { var name = new Name(command.FirstName, command.LastName); var email = new Email(command.Email); var password = new Password(command.Password); var user = new User(name, email, password, command.Birthdate, null, command.Image); AddNotifications(name.Notifications); AddNotifications(email.Notifications); AddNotifications(password.Notifications); AddNotifications(user.Notifications); bool save = _repository.Create(user); if (save) { _emailService.Send(user.Email.Address, MessagesUtil.Welcome, MessagesUtil.EmailWelcome); } if (!save) { return(new CommandResult(false, MessagesUtil.CreateError, Notifications)); } return(new CommandResult(true, MessagesUtil.CreatedSuccess)); }
public async Task Succeed_With_Valid_Request( CreateAccountCommand createToAccountCommand, CreateAccountCommand createFromAccountCommand, CreateCreditCommand createCreditCommand, TestServer server) { var client = server.CreateClient(); var initialToAccount = await client.PostAsJsonAsync <CreateAccountCommand, AccountModel>("api/accounts", createToAccountCommand); var initialFromAccount = await client.PostAsJsonAsync <CreateAccountCommand, AccountModel>("api/accounts", createFromAccountCommand); var funds = await client.PostAsJsonAsync <FundsModel, FundsModel>($"api/accounts/{initialFromAccount.AccountId}/credits", createCreditCommand.Funds); initialFromAccount.Balance = funds.Amount; var createTransferCommand = new CreateTransferCommand() { Funds = createCreditCommand.Funds, ReceivingAccountId = initialToAccount.AccountId, SendingAccountId = initialFromAccount.AccountId }; await client.PostAsJsonAsync <CreateTransferCommand, FundsModel>($"api/accounts/transfers", createTransferCommand); var resultToAccount = await client.GetAsync <AccountModel>($"api/accounts/{initialToAccount.AccountId}"); var resultFromAccount = await client.GetAsync <AccountModel>($"api/accounts/{initialFromAccount.AccountId}"); Assert.True(resultFromAccount.Balance == initialFromAccount.Balance - createCreditCommand.Funds.Amount); Assert.True(resultToAccount.Balance == initialToAccount.Balance + createCreditCommand.Funds.Amount); }
public async Task <Result <bool> > Handle(CreateAccountCommand request, CancellationToken cancellationToken) { try { var accountType = await _accountTypeRepository.GetAccountTypeByName(request.AccountType); var newAccount = new Account { Name = request.Name, Zip = request.Zip, Country = request.Country, City = request.City, Street = request.Street, StreetNo = request.StreetNo, ContactEmail = request.ContactEmail, CreatedAt = DateTime.UtcNow, CreatedBy = request.CreatedBy, AccountTypeId = accountType == null ? 1 : accountType.Id }; await _accountRepository.Create(newAccount); return(Result <bool> .Ok(true)); } catch (Exception e) { return(Result <bool> .Failure(e.Message)); } }
public Account CreateAccount(CreateAccountCommand command) { Account account = AccountFactory.CreateAccount(command.AccountType); account.InitializePositions(); return(account); }
public Task Handle(CreateAccountCommand command) { Log.Information("Handling account created command for {aggregate} correlationId:{correlationId}", command.AggregateId, command.CorrelationId); var account = new BankAccount(command.AggregateId, command.Name); return(_repo.SaveAsync(account)); }
public async Task CreateAccount(CreateAccountCommand command, CancellationToken cancellationToken = default) { var account = Account.Create(command.Value); await _accountRepository.AddAsync(account, cancellationToken); await _accountRepository.SaveChangesAsync(cancellationToken); }
public CreateAccountViewModel(CreateAccount view) { _View = view; _Model = new CreateAccountModel(); _Model.ShowText = false; UseCreateAccountCommand = new CreateAccountCommand(this); UseReturnToLoginCACommand = new ReturnToLoginFromACCommand(this); }
public AccountEntity Map(CreateAccountCommand source) { var destination = new AccountEntity { Name = source.Name }; return(destination); }
public async Task <IActionResult> CreateAccount([FromBody] CreateAccountRequest createAccountRequest) { var createAccountDto = mapper.Map <CreateAccountDto>(createAccountRequest); var command = new CreateAccountCommand(createAccountDto); var result = await mediator.Send(command); return(CreatedAtAction("CreateAccount", result)); }
public IHttpActionResult Post(AccountModel accountModel) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var command = new CreateAccountCommand { UserName = accountModel.UserName, Password = accountModel.Password, OrganizationName = accountModel.OrganizationName }; _createAccountCommandHandler.Handle(command); return Ok(); }
private TestObjects Setup() { var vObjects = new TestObjects(); vObjects.HashProvider = new Mock<IHashProvider>(); vObjects.HashProvider.Setup(t => t.Hash(cPassword)).Returns(cHash); vObjects.HashProvider.Setup(t => t.CheckHash(cPassword, cHash)).Returns(true); vObjects.DocumentStore = GetEmbeddedDatabase; var vNewAccount = new CreateAccount { Name = cName, Email = cEmail, Password = cPassword }; var vAccountCommandFactory = new Mock<IAccountCommandFactory>(); var vSendConfirmationCommand = new Mock<ISendConfirmationCommand>(); vAccountCommandFactory .Setup(t => t.CreateSendConfirmationCommand(It.IsAny<Account>())) .Returns(vSendConfirmationCommand.Object); var vNewAccountCommand = new CreateAccountCommand( vObjects.DocumentStore, vObjects.HashProvider.Object, vAccountCommandFactory.Object, new CryptoRandomProvider(), vNewAccount); vNewAccountCommand.Execute(); var vLogin = new LoginAccount { Name = cName, Password = cPassword }; vObjects.GoodLoginAccountCommand = new LoginAccountCommand( vObjects.DocumentStore, vObjects.HashProvider.Object, vLogin); return vObjects; }
public void ExecuteUsesHashProviderForHashWithSalt(string tName, string tPassword, string tEmail) { var vHashProvider = new Mock<IHashProvider>(); var vDocumentStore = GetEmbeddedDatabase; var vAccountCommandFactory = new Mock<IAccountCommandFactory>(); var vSendConfirmationCommand = new Mock<ISendConfirmationCommand>(); vAccountCommandFactory .Setup(t => t.CreateSendConfirmationCommand(It.IsAny<Account>())) .Returns(vSendConfirmationCommand.Object); var vCreateAccount = new CreateAccount { Name = tName, Password = tPassword, Email = tEmail }; var vRandomProvider = new Mock<IRandomProvider>(); var vCreateAccountCommand = new CreateAccountCommand(vDocumentStore, vHashProvider.Object, vAccountCommandFactory.Object, vRandomProvider.Object, vCreateAccount); vCreateAccountCommand.Execute(); vHashProvider.Verify(t => t.Hash(tPassword)); }
private TestObjects Setup() { var vReturn = new TestObjects { SignInPersistance = new Mock<ISignInPersistance>(), DocumentStore = new EmbeddableDocumentStore {RunInMemory = true} }; vReturn.DocumentStore.Initialize(); vReturn.DocumentStore.RegisterListener(new RavenDbNoStaleData()); var vAccountCommandFactory = new Mock<IAccountCommandFactory>(); var vSendConfirmationCommand = new Mock<ISendConfirmationCommand>(); vAccountCommandFactory .Setup(t => t.CreateSendConfirmationCommand(It.IsAny<Account>())) .Returns(vSendConfirmationCommand.Object); //Make sure there is an account to get. Since this deals with getting an account. var vNewAccount = new CreateAccountCommand(vReturn.DocumentStore, new CustomHashProvider(), vAccountCommandFactory.Object, new CryptoRandomProvider(), new CreateAccount { Email = "*****@*****.**", Name = cTestName, Password = "******" }); vNewAccount.Execute(); vReturn.Query = new CheckLoginQuery(vReturn.SignInPersistance.Object, vReturn.DocumentStore); return vReturn; }
public void NewAccountIsAdminWhenMatchesConfigForAdmin(string tName, string tPassword, string tEmail) { var vHashProvider = new Mock<IHashProvider>(); var vDocumentStore = GetEmbeddedDatabase; var vAccountCommandFactory = new Mock<IAccountCommandFactory>(); var vSendConfirmationCommand = new Mock<ISendConfirmationCommand>(); vAccountCommandFactory .Setup(t => t.CreateSendConfirmationCommand(It.IsAny<Account>())) .Returns(vSendConfirmationCommand.Object); var vCreateAccount = new CreateAccount { Name = tName, Password = tPassword, Email = tEmail }; var vRandomProvider = new Mock<IRandomProvider>(); var vCreateAccountCommand = new CreateAccountCommand(vDocumentStore, vHashProvider.Object, vAccountCommandFactory.Object, vRandomProvider.Object, vCreateAccount); vCreateAccountCommand.Execute(); using (var vSession = vDocumentStore.OpenSession()) { var vAccount = vSession.Load<Account>("Accounts/"+tName); Assert.IsTrue(vAccount.Roles.Any(t => t == eRoles.Admin)); } }