Ejemplo n.º 1
0
        public void TransferHandler_Execute_Succesfull()
        {
            var accountHandler = new Moq.Mock <IAccountHandler>();

            var ammount       = new Models.Money();
            var origin        = new Models.Account();
            var destiny       = new Models.Account();
            var transactionId = Guid.NewGuid();

            var transaction = new Models.Transfer()
            {
                Ammount = ammount,
                Origin  = origin,
                Destiny = destiny
            };

            accountHandler
            .Setup(a => a.BlockAmmount(origin, ammount))
            .Returns(transactionId);

            var transferHandler         = new TransferHandler(accountHandler.Object);
            var proccessedTransactionId = transferHandler.Execute(transaction);

            Assert.Equal(transactionId, proccessedTransactionId);

            accountHandler.Verify(a => a.BlockAmmount(origin, ammount), Moq.Times.Once);
            accountHandler.Verify(a => a.SendMoney(destiny, ammount, transactionId), Moq.Times.Once);
            accountHandler.Verify(a => a.ConfirmTransaction(transactionId), Moq.Times.Once);
            accountHandler.Verify(a => a.RevertTransaction(Moq.It.IsAny <Guid>()), Moq.Times.Never);
        }
Ejemplo n.º 2
0
        public void TransferHandler_Execute_NotEnoughMoneyException()
        {
            var accountHandler = new Moq.Mock <IAccountHandler>();

            var ammount = new Models.Money();
            var origin  = new Models.Account();

            var transaction = new Models.Transfer()
            {
                Ammount = ammount,
                Origin  = origin,
                Destiny = new Models.Account()
            };

            accountHandler
            .Setup(a => a.BlockAmmount(origin, ammount))
            .Throws(new NotEnoughMoneyException());

            var    transferHandler = new TransferHandler(accountHandler.Object);
            Action throwException  = () => transferHandler.Execute(transaction);

            Assert.Throws <NotEnoughMoneyException>(throwException);

            accountHandler.Verify(a => a.BlockAmmount(origin, ammount), Moq.Times.Once);
            accountHandler.Verify(a => a.SendMoney(Moq.It.IsAny <Models.Account>(), Moq.It.IsAny <Models.Money>(), Moq.It.IsAny <Guid>()), Moq.Times.Never);
            accountHandler.Verify(a => a.ConfirmTransaction(Moq.It.IsAny <Guid>()), Moq.Times.Never);
            accountHandler.Verify(a => a.RevertTransaction(Moq.It.IsAny <Guid>()), Moq.Times.Never);
        }
        public void TestServerConnectVerifyCbShowAbonent()
        {
            var abonent = new Server.Abonent()
            {
                id     = 2,
                name   = "2",
                status = Server.Status.Online
            };



            Dictionary <int, Server.Abonent> allAbonents = new Dictionary <int, Server.Abonent>();

            mockDataBase.Setup(r => r.AddAbonentToDb(1, "1"));
            mockDataBase.Setup(r => r.GetAbonentFromDb()).Returns(allAbonents);

            mockLogger.Setup(r => r.Logging("test"));

            mockOperationContext.Setup(r => r.GetChannelCallback(It.IsAny <OperationContext>())).Returns(mockCallback.Object);

            var server = new Server.Server(mockDataBase.Object, mockLogger.Object, mockOperationContext.Object);

            server.Connect("1");
            server.Connect("2");

            //
            mockCallback.Verify(x => x.cbShowAbonent(It.IsAny <Server.Abonent>()));
        }
        public async Task Synchronize_Works_StartWithEmplyDb_HQEmpty()
        {
            var cs          = CommonHelpers.MockConfServ(false);
            var hqApiClient = new Moq.Mock <IHQAPIClient>();

            // no employees in HQ
            hqApiClient.Setup(m => m.ListEmployees(cs.GetBranchOfficeId())).Returns(
                Task.FromResult(new List <HQEmployee>())
                );
            // no salaries in HQ
            hqApiClient.Setup(m => m.ListSalariesForEmployee(Moq.It.IsAny <int>())).Returns(
                Task.FromResult(new List <HQSalary>())
                );

            var dao = new PostgresDataAccessObjectService(dbContext);
            var ss  = new SynchronizatorService(hqApiClient.Object, cs, dao);
            await ss.Synchronize();

            hqApiClient.Verify(m => m.ListEmployees(0), Moq.Times.Once);
            // ListEmployees did not succeed, so no new http requests are handled
            hqApiClient.Verify(m => m.ListSalariesForEmployee(Moq.It.IsAny <int>()), Moq.Times.Never);
            ss.Dispose();

            var emps = dao.GetAllEmployees();
            var eh   = dao.GetAllEmployeeHours();

            Assert.Empty(emps);
            Assert.Empty(eh);
        }
        public void AccountHandler_SendMoney_Succesfull()
        {
            var  accountService = new Moq.Mock <IAccountService>();
            var  accountHandler = new AccountHandler(accountService.Object);
            var  transactionId  = Guid.NewGuid();
            Guid accountId      = Guid.NewGuid();
            var  account        = new Models.Account();
            var  ammount        = new Models.Money();
            var  accountDetail  = new Models.AccountDetail()
            {
                Id      = accountId,
                Account = account,
                Balance = new Money()
                {
                    Total    = 1000,
                    Currency = "BRL"
                }
            };

            accountService
            .Setup(a => a.FindAccount(account))
            .Returns(accountDetail);

            accountHandler.SendMoney(account, ammount, transactionId);

            accountService.Verify(a => a.FindAccount(account), Moq.Times.Once);
            accountService.Verify(a => a.SendMoney(accountId, ammount, transactionId), Moq.Times.Once);
        }
Ejemplo n.º 6
0
        public void TransferHandler_Execute_AccountNotFoundException()
        {
            var accountHandler = new Moq.Mock <IAccountHandler>();

            var ammount       = new Models.Money();
            var origin        = new Models.Account();
            var destiny       = new Models.Account();
            var transactionId = Guid.NewGuid();

            var transaction = new Models.Transfer()
            {
                Ammount = ammount,
                Origin  = origin,
                Destiny = destiny
            };

            accountHandler
            .Setup(a => a.BlockAmmount(origin, ammount))
            .Returns(transactionId);

            accountHandler
            .Setup(a => a.SendMoney(destiny, ammount, transactionId))
            .Throws(new AccountNotFoundException());

            var    transferHandler = new TransferHandler(accountHandler.Object);
            Action throwException  = () => transferHandler.Execute(transaction);

            Assert.Throws <AccountNotFoundException>(throwException);

            accountHandler.Verify(a => a.BlockAmmount(origin, ammount), Moq.Times.Once);
            accountHandler.Verify(a => a.SendMoney(destiny, ammount, transactionId), Moq.Times.Once);
            accountHandler.Verify(a => a.ConfirmTransaction(transactionId), Moq.Times.Never);
            accountHandler.Verify(a => a.RevertTransaction(transactionId), Moq.Times.Once);
        }
Ejemplo n.º 7
0
        public async Task size_delayed_dont_check_expired()
        {
            var bag     = new ContextBag();
            int invoked = 0;
            var handler = new MessageHandler((first, second, ctx) =>
            {
                invoked++;
                return(Task.CompletedTask);
            }, typeof(DelayedHandler));
            var context = new Moq.Mock <IInvokeHandlerContext>();
            var builder = new Moq.Mock <IBuilder>();
            var channel = new Moq.Mock <IDelayedChannel>();
            var next    = new Moq.Mock <Func <PipelineTerminator <IInvokeHandlerContext> .ITerminatingContext, Task> >();

            builder.Setup(x => x.Build <IDelayedChannel>()).Returns(channel.Object);
            context.Setup(x => x.MessageHandler).Returns(handler);
            context.Setup(x => x.Builder).Returns(builder.Object);
            context.Setup(x => x.Extensions).Returns(bag);
            context.Setup(x => x.MessageBeingHandled).Returns(new DelayedMessageNoProps());
            context.Setup(x => x.Headers).Returns(new Dictionary <string, string>());
            channel.Setup(x => x.Size(Moq.It.IsAny <string>(), Moq.It.IsAny <string>())).Returns(Task.FromResult(1));


            channel.Setup(x => x.Pull("test", Moq.It.IsAny <string>(), Moq.It.IsAny <int?>()))
            .Returns(Task.FromResult(new IDelayedMessage[] { new Aggregates.Internal.DelayedMessage(), new Aggregates.Internal.DelayedMessage() }.AsEnumerable()));

            await _terminator.Invoke(context.Object, next.Object);

            channel.Verify(x => x.AddToQueue(Moq.It.IsAny <string>(), Moq.It.IsAny <IDelayedMessage>(), Moq.It.IsAny <string>()), Moq.Times.Once);
            // Posibly optional
            channel.Verify(x => x.Age(Moq.It.IsAny <string>(), Moq.It.IsAny <string>()), Moq.Times.Never);
            channel.Verify(x => x.Size(Moq.It.IsAny <string>(), Moq.It.IsAny <string>()), Moq.Times.Once);
            channel.Verify(x => x.Pull(Moq.It.IsAny <string>(), Moq.It.IsAny <string>(), 1), Moq.Times.Never);
        }
Ejemplo n.º 8
0
        public async Task sets_context_bag()
        {
            var bag     = new ContextBag();
            var context = new Moq.Mock <IIncomingPhysicalMessageContext>();
            var next    = new Moq.Mock <Func <Task> >();

            context.Setup(x => x.MessageId).Returns("1");
            context.Setup(x => x.Message).Returns(new IncomingMessage("1", new Dictionary <string, string>(), new byte[] { }));
            context.Setup(x => x.Extensions).Returns(bag);

            next.Setup(x => x()).Throws(new Exception("test"));
            Assert.ThrowsAsync <Exception>(() => _rejector.Invoke(context.Object, next.Object));
            next.Verify(x => x(), Moq.Times.Once);
            int retries;

            Assert.True(bag.TryGet <int>(Defaults.Retries, out retries));
            Assert.AreEqual(0, retries);

            next.Setup(x => x()).Returns(Task.CompletedTask);
            await _rejector.Invoke(context.Object, next.Object);

            next.Verify(x => x(), Moq.Times.Exactly(2));

            Assert.True(bag.TryGet <int>(Defaults.Retries, out retries));
            Assert.AreEqual(1, retries);
        }
        public async Task ignore_resolver()
        {
            var store     = new Moq.Mock <IStoreEvents>();
            var streamGen = new StreamIdGenerator((type, stream, bucket, id, parents) => "test");

            var fullevent = new Moq.Mock <IFullEvent>();

            fullevent.Setup(x => x.Event).Returns(new Event());

            _stream.Setup(x => x.Add(Moq.It.IsAny <IEvent>(), Moq.It.IsAny <IDictionary <string, string> >()));
            store.Setup(
                x => x.WriteEvents("test", new[] { fullevent.Object }, Moq.It.IsAny <IDictionary <string, string> >(), null))
            .Returns(Task.FromResult(0L));

            // Ignores conflict, just commits
            var resolver = new IgnoreConflictResolver(store.Object, streamGen);

            var entity = new Entity(_stream.Object, _resolver.Object);


            await resolver.Resolve(entity, new[] { fullevent.Object }, Guid.NewGuid(), new Dictionary <string, string>())
            .ConfigureAwait(false);

            _stream.Verify(x => x.Add(Moq.It.IsAny <IEvent>(), Moq.It.IsAny <IDictionary <string, string> >()),
                           Moq.Times.Once);
            store.Verify(
                x => x.WriteEvents("test", new[] { fullevent.Object }, Moq.It.IsAny <IDictionary <string, string> >(), null),
                Moq.Times.Once);
        }
        public void AccountHandler_BlockMoney_Succesfull()
        {
            var  accountService = new Moq.Mock <IAccountService>();
            var  accountHandler = new AccountHandler(accountService.Object);
            var  serviceId      = Guid.NewGuid();
            Guid accountId      = Guid.NewGuid();
            var  origin         = new Models.Account();
            var  accountDetail  = new Models.AccountDetail()
            {
                Id      = accountId,
                Account = origin,
                Balance = new Money()
                {
                    Total    = 1000,
                    Currency = "BRL"
                }
            };
            var ammount = new Models.Money();

            accountService
            .Setup(a => a.FindAccount(origin))
            .Returns(accountDetail);

            accountService
            .Setup(a => a.BlockAmmount(accountId, ammount))
            .Returns(serviceId);

            var transactionId = accountHandler.BlockAmmount(origin, ammount);

            Assert.Equal(serviceId, transactionId);

            accountService.Verify(a => a.FindAccount(origin), Moq.Times.Once);
            accountService.Verify(a => a.BlockAmmount(accountId, ammount), Moq.Times.Once);
        }
Ejemplo n.º 11
0
        public void TestMethod2()
        {
            string input = "Hi";

            ticsReportParser.Persist(input);
            _mockWrapper.Verify(fakeneighbour => fakeneighbour.PersistToDatabase(input), Moq.Times.Exactly(1));
        }
Ejemplo n.º 12
0
        public void TransferMoney_Succesfully()
        {
            Guid from = Guid.NewGuid();
            Guid to   = Guid.NewGuid();


            var fromAccount = new Domain.Account(from, new Domain.User(Guid.NewGuid(), "alice", "*****@*****.**"), 100m, 90m, 0m);
            var toAccount   = new Domain.Account(to, new Domain.User(Guid.NewGuid(), "bob", "*****@*****.**"), 120m, 80m, 0m);

            Moq.Mock <IAccountRepository> moq = new Moq.Mock <IAccountRepository>();

            moq.Setup(x => x.GetAccountById(from)).Returns(fromAccount);
            moq.Setup(x => x.GetAccountById(to)).Returns(toAccount);

            IAccountRepository repository = moq.Object;

            TransferMoney transferMoney = new TransferMoney(repository);

            bool result = transferMoney.Execute(from, to, 10);

            Assert.True(result);
            Assert.Equal(90m, fromAccount.Balance);
            Assert.Equal(130m, toAccount.Balance);

            moq.Verify(v => v.Update(fromAccount));
            moq.Verify(v => v.Update(toAccount));
        }
Ejemplo n.º 13
0
        public void commit_with_stream()
        {
            var eventSource = _repository.New(Guid.NewGuid());

            Assert.DoesNotThrow(() => _repository.Commit(Guid.NewGuid(), null));
            _eventStream.Verify(x => x.Commit(Moq.It.IsAny <Guid>(), null), Moq.Times.Once);
        }
Ejemplo n.º 14
0
        public void Commit_one_repo()
        {
            var repo = _uow.For <_AggregateStub <Guid> >();

            Assert.DoesNotThrow(() => (_uow as ICommandUnitOfWork).End());
            _guidRepository.Verify(x => x.Commit(Moq.It.IsAny <Guid>(), Moq.It.IsAny <IDictionary <String, String> >()), Moq.Times.Once);
        }
Ejemplo n.º 15
0
        public void ExecuteLogin_LogsIn_AndRaisesLoggedInEvent()
        {
            _viewModel.SatelliteAddress = "europe-west-1.tardigrade.io:7777";
            _viewModel.Secret           = "mySecret";
            _viewModel.SecretVerify     = "mySecretVerify";
            _viewModel.ApiKey           = "apiKey";
            StoreAccess access = new StoreAccess("myAccess");
            SuccessfullyLoggedInMessage loggedInMessage = new SuccessfullyLoggedInMessage();

            _storeAccessServiceMock.Setup(s => s.GenerateAccessFromLogin(Moq.It.Is <LoginData>(l => l.ApiKey == _viewModel.ApiKey &&
                                                                                               l.SatelliteAddress == _viewModel.SatelliteAddress &&
                                                                                               l.Secret == _viewModel.Secret))).Returns(access).Verifiable();

            _loginServiceMock.Setup(s => s.Login(access)).Returns(true).Verifiable();

            _eventAggregator.Setup(s => s.GetEvent <SuccessfullyLoggedInMessage>()).Returns(loggedInMessage).Verifiable();

            _viewModel.LoginCommand.Execute();

            Assert.IsFalse(_viewModel.LoginFailed);

            _storeAccessServiceMock.Verify();
            _loginServiceMock.Verify();
            _eventAggregator.Verify();
        }
Ejemplo n.º 16
0
        public async Task add_channel_not_cached_yet()
        {
            var msg = new Moq.Mock <IDelayedMessage>();
            await _channel.AddToQueue("test", msg.Object, "test");

            _cache.Verify(x => x.Add(Moq.It.IsAny <string>(), Moq.It.IsAny <string>(), Moq.It.IsAny <IDelayedMessage[]>()), Moq.Times.Never);
        }
        public async Task no_problem_one_units_of_work()
        {
            var bag     = new ContextBag();
            var context = new Moq.Mock <IIncomingLogicalMessageContext>();
            var next    = new Moq.Mock <Func <Task> >();
            var builder = new Moq.Mock <IBuilder>();
            var uow     = new Moq.Mock <IApplicationUnitOfWork>();

            builder.Setup(x => x.BuildAll <IApplicationUnitOfWork>()).Returns(new IApplicationUnitOfWork[] { uow.Object });
            context.Setup(x => x.MessageId).Returns("1");
            context.Setup(x => x.Message).Returns(new LogicalMessage(new NServiceBus.Unicast.Messages.MessageMetadata(typeof(object)), new object()));
            context.Setup(x => x.Extensions).Returns(bag);
            context.Setup(x => x.Builder).Returns(builder.Object);
            context.Setup(x => x.Headers).Returns(new Dictionary <string, string>());
            context.Setup(x => x.MessageHeaders)
            .Returns(new Dictionary <string, string> {
                [Headers.MessageIntent] = MessageIntentEnum.Send.ToString()
            });

            await _uow.Invoke(context.Object, next.Object);

            next.Verify(x => x(), Moq.Times.Once);
            uow.Verify(x => x.Begin(), Moq.Times.Once);
            uow.Verify(x => x.End(null), Moq.Times.Once);
        }
Ejemplo n.º 18
0
        public async Task is_delayed_delayed()
        {
            var  bag     = new ContextBag();
            bool invoked = false;
            var  handler = new MessageHandler((first, second, ctx) =>
            {
                invoked = true;
                return(Task.CompletedTask);
            }, typeof(DelayedHandler));
            var context = new Moq.Mock <IInvokeHandlerContext>();
            var builder = new Moq.Mock <IBuilder>();
            var channel = new Moq.Mock <IDelayedChannel>();
            var next    = new Moq.Mock <Func <PipelineTerminator <IInvokeHandlerContext> .ITerminatingContext, Task> >();

            builder.Setup(x => x.Build <IDelayedChannel>()).Returns(channel.Object);
            context.Setup(x => x.MessageHandler).Returns(handler);
            context.Setup(x => x.Builder).Returns(builder.Object);
            context.Setup(x => x.Extensions).Returns(bag);
            context.Setup(x => x.MessageBeingHandled).Returns(new DelayedMessage());
            context.Setup(x => x.Headers).Returns(new Dictionary <string, string>());

            await _terminator.Invoke(context.Object, next.Object);

            Assert.False(invoked);
            channel.Verify(x => x.AddToQueue(Moq.It.IsAny <string>(), Moq.It.IsAny <IDelayedMessage>(), Moq.It.IsAny <string>()), Moq.Times.Once);
            // Posibly optional
            channel.Verify(x => x.Age(Moq.It.IsAny <string>(), Moq.It.IsAny <string>()), Moq.Times.Once);
            channel.Verify(x => x.Size(Moq.It.IsAny <string>(), Moq.It.IsAny <string>()), Moq.Times.Once);
        }
Ejemplo n.º 19
0
        public async Task enables_by_category()
        {
            _consumer.Setup(x => x.EnableProjection("$by_category")).Returns(Task.FromResult(true));

            await _subscriber.Setup("test", Version.Parse("0.0.0")).ConfigureAwait(false);

            _consumer.Verify(x => x.EnableProjection("$by_category"), Moq.Times.Once);
        }
Ejemplo n.º 20
0
 public void Teardown()
 {
     // Verify stream is always unfrozen
     if (_wasFrozen)
     {
         _store.Verify(x => x.Unfreeze <Entity>(Moq.It.IsAny <IEventStream>()), Moq.Times.Once);
     }
 }
        public void TestClientConnect()
        {
            /// allAbonents.Count;
            mockClient.Setup(x => x.ShowAbonents(0)).Returns(allAbonents);
            chat.ConnectMethod(mockClient.Object, "1");

            mockClient.Verify(x => x.Connect("1"));
        }
Ejemplo n.º 22
0
            public void Given_valid_arguements_when_Add_invoke_Then_Valid_Result_Asserted()
            {
                calculate.Addition(10, 20);
                calculate.Addition(10, 20);
                calculate.Addition(10, 20);
                calculate.Addition(10, 20);

                _mockWrapper.Verify(fakeNeighbour => fakeNeighbour.write("Add method Invoked"), Moq.Times.Exactly(4));
            }
Ejemplo n.º 23
0
        public async Task events_get_oobevent()
        {
            _eventstore.Setup(x => x.GetEvents <FakeEntity>(Moq.It.IsAny <string>(), Moq.It.IsAny <Id>(), Moq.It.IsAny <Id[]>(), Moq.It.IsAny <long?>(), Moq.It.IsAny <int?>()))
            .Returns(Task.FromResult(new IFullEvent[] { }));

            await _entity.GetEvents(0, 1, oob : "test").ConfigureAwait(false);

            _oobWriter.Verify(x => x.GetEvents <FakeEntity>(Moq.It.IsAny <string>(), Moq.It.IsAny <Id>(), Moq.It.IsAny <Id[]>(), "test", Moq.It.IsAny <long?>(), Moq.It.IsAny <int?>()), Moq.Times.Once);
        }
        public void Init_SetsStoreAccess_OnViewModel()
        {
            _viewModel.Init(_storeAccess);

            Assert.AreEqual(_viewModel._storeAccess, _storeAccess);

            _bookShelfServiceMock.Verify();
            _eventAggregator.Verify();
        }
Ejemplo n.º 25
0
        public async Task event_delivered()
        {
            _contextBag.Set(Defaults.LocalHeader, new object());

            await _executor.Invoke(_context.Object, _next.Object);

            _context.Verify(x => x.UpdateMessageInstance(Moq.It.IsAny <object>()), Moq.Times.Exactly(2));
            _next.Verify(x => x(), Moq.Times.Once);
        }
Ejemplo n.º 26
0
        public async Task commit_empty()
        {
            await(_repository as IRepository).Commit(Guid.NewGuid(), new Dictionary <string, string>()).ConfigureAwait(false);


            _store.Verify(
                x =>
                x.Write <Poco>(Moq.It.IsAny <Tuple <long, Poco> >(), Moq.It.IsAny <string>(), Moq.It.IsAny <Id>(),
                               Moq.It.IsAny <Id[]>(), Moq.It.IsAny <IDictionary <string, string> >()), Moq.Times.Never);
        }
Ejemplo n.º 27
0
        public async Task normal()
        {
            await _executor.Invoke(_context.Object, _next.Object);

            _domainUow.Verify(x => x.Begin(), Moq.Times.Once);
            _uow.Verify(x => x.Begin(), Moq.Times.Once);
            _domainUow.Verify(x => x.End(Moq.It.IsAny <Exception>()), Moq.Times.Once);
            _uow.Verify(x => x.End(Moq.It.IsAny <Exception>()), Moq.Times.Once);
            _next.Verify(x => x(), Moq.Times.Once);
        }
Ejemplo n.º 28
0
        public void Edit_Action_Saves_Ingredient_To_Repository_And_Redirects_To_Index()
        {
            AdminController controller    = new AdminController(mockRepos.Object);
            Ingredient      newIngredient = new Ingredient();

            var result = (RedirectToRouteResult)controller.Edit(newIngredient);

            mockRepos.Verify(x => x.SaveIngredient(newIngredient));
            Assert.AreEqual("Index", result.RouteValues["action"]);
        }
        public void GivenPatientVitals_WhenStorePatientVitalsDataCalled_ExpectedMokerFunctionCalledOnce()
        {
            PatientVitals patientVitalsData = new PatientVitals()
            {
                PatientId = "101", Spo2 = 88, Temperature = 97, PulseRate = 70
            };

            patientVitalsStorage.StorePatientVitalsData(patientVitalsData);
            _mockObj.Verify(neighbour => neighbour.WritePatientVitalsData(patientVitalsData), Moq.Times.Exactly(1));
        }
Ejemplo n.º 30
0
        public async Task no_problem_with_mutators()
        {
            _mutator.Setup(x => x.MutateIncoming(Moq.It.IsAny <IMutating>())).Returns <IMutating>(x => x);
            _builder.Setup(x => x.BuildAll <ICommandMutator>()).Returns(new[] { _mutator.Object });
            _context.Setup(x => x.Message).Returns(new LogicalMessage(new NServiceBus.Unicast.Messages.MessageMetadata(typeof(FakeCommand)), new FakeCommand()));

            await _pipeline.Invoke(_context.Object, _next.Object);

            _mutator.Verify(x => x.MutateIncoming(Moq.It.IsAny <IMutating>()), Moq.Times.Once);
        }
Ejemplo n.º 31
0
        public void should_execute_the_handler_when_an_event_is_raised()
        {
            var handler = new Moq.Mock<CreateLotsForBrokerageTransactions>();
            var @event = new BrokerageTransactionsPersisted(null);

            new EventBus(handler.Object).Raise(@event);

            handler.Verify(x => x.Handle(@event));
        }
Ejemplo n.º 32
0
        public void CanSaveEditedProducts()
        {
            var mockRepository = new Moq.Mock<IProductsRepository>();
            var product = new Product();

            var result = new AdminController(mockRepository.Object).Edit(product, null);

            mockRepository.Verify(x => x.SaveProduct(product));
            result.ShouldBeRedirectionTo(new { action = "Index" });
        }
        public void TestStartListner()
        {
            Moq.Mock<Socket> mock = new Moq.Mock<Socket>(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            SocketListener listener = new SocketListener(mock.Object);
            listener.Start();

            Assert.IsTrue(listener.Started);
            Assert.AreEqual(listener.Server,mock.Object);
            mock.Verify(s => s.AcceptAsync(Moq.It.IsAny<SocketAsyncEventArgs>()));
        }
Ejemplo n.º 34
0
        public void MoqTest()
        {
            Moq.Mock<IPushToServer> moq = new Moq.Mock<IPushToServer>();
            TestMeClass testme = new TestMeClass(moq.Object);
            //setup
            moq.Setup(x => x.GetString()).Returns("Hello");

            //action
            testme.Do();

            //verify
            moq.Verify(x=>x.Push("Hello"),Moq.Times.AtLeast(3));
        }
        public void ShouldNotFailWhenMetricsIsInstalled()
        {
            if (!this.MetricsInstalled)
            {
                Assert.IsTrue(true);
                return;
            }

            var mock = new Moq.Mock<IMetricsLogger>();

            // Create a WorkflowInvoker and add the IBuildDetail Extension
            var target = MetricsInvoker.Create(new List<string> { "*.dll" }, @"c:\binaries", "Metrics.exe", mock.Object);
            Assert.IsNotNull(target);
            mock.Verify(m => m.LogError(Moq.It.IsAny<string>()), Moq.Times.Never());
        }
Ejemplo n.º 36
0
        public void TestHeadsetConnected()
        {
            var statusMock = new Moq.Mock<ICicStatusService>();
            var deviceManagerMock = new Moq.Mock<IDeviceManager>();
            var settingsManagerMock = new Moq.Mock<ISettingsManager>();

            settingsManagerMock.SetupGet(s => s.HeadsetConnectStatusKey).Returns(STATUS_KEY);
            settingsManagerMock.SetupGet(s => s.HeadsetConnectChangeStatus).Returns(true);

            var target = new StatusChanger(null, statusMock.Object, deviceManagerMock.Object, settingsManagerMock.Object);

            deviceManagerMock.Raise(d => d.HeadsetConnected += null, new Plantronics.UC.SpokesWrapper.ConnectedStateArgs(true, true));

            statusMock.Verify(cic => cic.SetStatus(STATUS_KEY));
        }
        public void ShouldFailWhenMetricsNotInstalled()
        {
            if (this.MetricsInstalled)
            {
                Assert.IsTrue(true);
                return;
            }

            var mock = new Moq.Mock<IMetricsLogger>();

            // Create a WorkflowInvoker and add the IBuildDetail Extension
            var target = MetricsInvoker.Create(new List<string> { "*.dll" }, @"c:\binaries", "Metrics.exe", mock.Object);
            Assert.IsNull(target);
            mock.Verify(m => m.LogError(Moq.It.Is<string>(s => s.Contains("Could not locate"))));
        }
Ejemplo n.º 38
0
        public void CountAdsByCities_CallAdRepository_ReturnResultOfRepo()
        {
            // Given
            IDictionary<City, int> result = new Dictionary<City, int>();
            var adRepoMock = new Moq.Mock<IAdRepository>();
            adRepoMock.Setup(r => r.CountAdsByCity()).Returns(result);

            AdServices service = new AdServices(adRepoMock.Object, null, null);

            // When
            IDictionary<City, int> actual = service.CountAdsByCities();

            // Then
            Assert.AreEqual(result, actual);
            adRepoMock.Verify();
        }
Ejemplo n.º 39
0
        public void Valid_Order_Goes_To_Submitter_And_Displays_Completed_View()
        {
            // Arrange
            var mockSubmitter = new Moq.Mock<IOrderSubmitter>();
            CartController controller = new CartController(null, mockSubmitter.Object);
            Cart cart = new Cart();
            cart.AddItem(new Product(), 1);
            var formData = new FormCollection {
            { "Name", "Steve" }, { "Line1", "123 My Street" },
            { "Line2", "MyArea" }, { "Line3", "" },
            { "City", "MyCity" }, { "State", "Some State" },
            { "Zip", "123ABCDEF" }, { "Country", "Far far away" },
            { "GiftWrap", bool.TrueString }
            };

            // Act
            var result = controller.CheckOut(cart, formData);

            // Assert
            Assert.AreEqual("Completed", result.ViewName);
            mockSubmitter.Verify(x => x.SubmitOrder(cart));
            Assert.AreEqual(0, cart.Lines.Count);
        }
Ejemplo n.º 40
0
        public void It_should_be_possible_to_parse_and_eval_script_with_modules()
        {
            var scriptService = new Moq.Mock<IScriptService>();
            scriptService.Setup(p => p.Parse("TestModule.Name", Moq.It.IsAny<ScriptParameterList>())).Returns(new Mocks.ScriptExpressionMock("TestModule.Name", typeof(string)));
            TestModule testModule = new TestModule();

            ModuleDefinitionList modules = new ModuleDefinitionList();
            modules.Add(new ModuleDefinition("TestModule", TestModule.Definition));
            PageParameterList parameters = new PageParameterList();

            PageScriptService target = new PageScriptService(scriptService.Object);

            XValue exp;
            exp = target.Parse("@TestModule.Name", typeof(string), modules, parameters);

            scriptService.Verify(p => p.Parse("TestModule.Name", Moq.It.IsAny<ScriptParameterList>()));

            Dictionary<string, object> modulesInstance = new Dictionary<string, object>();
            modulesInstance.Add("TestModule", testModule);
            ContextParameterList parametersInstance = new ContextParameterList();

            target.Eval(exp, modulesInstance, parametersInstance);

            scriptService.Verify(p => p.Eval(Moq.It.IsAny<IScriptExpression>(), Moq.It.IsAny<ScriptParameterList>()));
        }
Ejemplo n.º 41
0
        public void SpamRequestAd_AdExists_SaveSpamRequest()
        {
            // Given
            var adRepoMock = new Moq.Mock<IAdRepository>();
            adRepoMock.Setup(x => x.CanDeleteAd(7)).Returns(true);

            var repoMock = new Moq.Mock<IRepository>();
            repoMock.Setup(x => x.Get<SpamAdType>(3)).Returns(new SpamAdType() { Id = 3 });

            var hSMock = new Moq.Mock<IHelperService>();
            hSMock.Setup(x => x.GetCurrentDateTime()).Returns(new DateTime(2013, 05, 17, 6, 7, 22));

            SpamAdRequestModel model = new SpamAdRequestModel();
            model.AdId = 7;
            model.Description = "description";
            model.RequestorEmail = "*****@*****.**";
            model.SelectedSpamAdTypeId = 3;

            SpamAdServices service = new SpamAdServices(adRepoMock.Object, repoMock.Object, hSMock.Object);

            // When
            SpamAdRequestModel result = service.SpamRequestAd(model);

            // Then
            Assert.IsFalse(result.CanSignal);
            Assert.AreEqual("Votre signalement a correctement été transmis. Merci de votre précieuse aide dans la chasse aux mauvaises annonces !", result.InfoMessage);

            repoMock.Verify(x => x.Save(Moq.It.Is<SpamAdRequest>(b =>
                b.Description == model.Description
                && b.RequestDate == new DateTime(2013, 05, 17, 6, 7, 22)
                && b.RequestorEmailAddress == model.RequestorEmail
                && b.SpamType.Id == 3)));
        }