public void ActivateAd_ActivationTokenDoesNotWork_ReturnModelIsActivatedFalse()
        {
            // Given
            BaseAd ad = new Ad()
            {
                IsActivated = false,
                ActivationToken = "AAA"
            };
            long adId = 78;

            var repoMock = new Moq.Mock<IRepository>();
            repoMock.Setup(x => x.Get<BaseAd>(adId)).Returns(ad);

            AdActivationServices service = new AdActivationServices(repoMock.Object, null, null, null);

            // When
            AdActivationResultModel model = service.ActivateAd(adId, "BBB");

            // Then
            Assert.IsFalse(model.IsActivated);
            Assert.AreEqual(78, model.AdId);
            Assert.AreEqual("Vous ne pouvez pas activer cette annonce.", model.InfoMessage);

            repoMock.Verify(x => x.Save(ad), Moq.Times.Never());
            repoMock.Verify(x => x.Save(Moq.It.IsAny<SearchAdCache>()), Moq.Times.Never());
        }
		public void shouldHaveSynchronizeWithGoogleFunction() {
			var avegaContactServiceMock = new Moq.Mock<IAvegaContactService>();
			avegaContactServiceMock.Setup(x => x.SynchronizeWithGoogleContact(It.IsAny<AvegaContact>()))
				.Returns(new SynchronizationStatus(true, false, false));

			var avetaContactService = avegaContactServiceMock.Object;
			avetaContactService.SynchronizeWithGoogleContact(new AvegaContact("MyContact"));

			avegaContactServiceMock.Verify();
		}
        public void ActivateAd_ActivationTokenWorks_ReturnModelIsActivatedTrueAndActivatesAd()
        {
            // Given
            BaseAd ad = new Ad()
            {
                IsActivated = false,
                ActivationToken = "AAA",
                City = new City(),
                Category = new Category()
            };
            long adId = 78;

            var repoMock = new Moq.Mock<IRepository>();
            repoMock.Setup(x => x.Get<BaseAd>(adId)).Returns(ad);

            AdActivationServices service = new AdActivationServices(repoMock.Object, null, null, null);

            // When
            AdActivationResultModel model = service.ActivateAd(78, "AAA");

            // Then
            Assert.IsTrue(model.IsActivated);
            Assert.AreEqual(78, model.AdId);
            Assert.AreEqual("Merci d'avoir activé votre annonce.", model.InfoMessage);

            repoMock.Verify(x => x.Save(ad), Moq.Times.Once());
            repoMock.Verify(x => x.Save(Moq.It.IsAny<SearchAdCache>()), Moq.Times.Once());
        }
        public void Can_use_Dsl_to_send_templated_email()
        {
            using (ShimsContext.Create())
            {
                // arrange
                var wi = new ShimWorkItem()
                {
                    TitleGet = () => "The wi title", IdGet = () => 99
                };
                var emailProvider = new Moq.Mock <IEmailProvider>();
                var tfsProvider   = new Moq.Mock <ITfsProvider>();
                tfsProvider.Setup(t => t.GetWorkItem(99)).Returns(wi);
                var engine = new TFSEventsProcessor.Dsl.DslProcessor();

                var args = new Dictionary <string, object> {
                    { "Arguments", new[] { "WorkItemEvent", "99" } },
                };

                // act
                engine.RunScript(
                    @".\dsl",
                    @"dsl\tfs",
                    "sendtemplatedemail.py",
                    args,
                    tfsProvider.Object,
                    emailProvider.Object,
                    Helpers.TestData.DummyWorkItemChangedAlertXml());

                // assert
                emailProvider.Verify(
                    e =>
                    e.SendEmailAlert(Moq.It.IsAny <IFieldLookupProvider>(), @"dsl\tfs\EmailTemplate.htm", true, true));
            }
        }
 private void TestBad()
 {
     var mock1 = new Moq.Mock <Foo>(1, true);
     var mock2 = new Mock <ConstructorArgumentsShouldMatch.Foo>(2, true);
     var mock3 = new Mock <ConstructorArgumentsShouldMatch.Foo>("1", 3);
     var mock4 = new Mock <ConstructorArgumentsShouldMatch.Foo>(new int[] { 1, 2, 3 });
 }
Ejemplo n.º 6
0
        public void Setup()
        {
            var now = DateTime.UtcNow;

            _validModel = new ApprenticeshipUploadModel
            {
                ApprenticeshipViewModel = new ApprenticeshipViewModel
                {
                    ULN         = "1001234567",
                    FirstName   = "TestFirstName",
                    LastName    = "TestLastName",
                    CourseCode  = "12",
                    DateOfBirth = new DateTimeViewModel(now.AddYears(-16)),
                    StartDate   = new DateTimeViewModel(now),
                    EndDate     = new DateTimeViewModel(now.AddYears(3)),
                    Cost        = "1234"
                },
                CsvRecord = new CsvRecord {
                    CohortRef = "abba123"
                }
            };

            _mockAcademicYear = new Moq.Mock <IAcademicYearDateProvider>();
            _mockUlnValidator = new Moq.Mock <IUlnValidator>();
            _mockUlnValidator.Setup(m => m.Validate(_validModel.ApprenticeshipViewModel.ULN)).Returns(UlnValidationResult.Success);
            _mockAcademicYear.Setup(m => m.CurrentAcademicYearEndDate).Returns(new DateTime(2030, 12, 1));

            _validator = new ApprenticeshipUploadModelValidator(new BulkUploadApprenticeshipValidationText(_mockAcademicYear.Object), new CurrentDateTime(), _mockUlnValidator.Object, _mockAcademicYear.Object);
        }
        public async Task TestGetBackupMetadataAsync_OneFullBackup_AndTwoIncrementalBackup_Present()
        {
            //arrange
            Guid     partitionId = Guid.NewGuid();
            DateTime now         = DateTime.UtcNow;

            BackupMetadata backupMetadata         = new BackupMetadata(partitionId, now, BackupOption.Full);
            BackupMetadata incrementalMetadata    = new BackupMetadata(partitionId, now.AddHours(1), BackupOption.Incremental);
            BackupMetadata incrementalMetadataTwo = new BackupMetadata(partitionId, now.AddHours(2), BackupOption.Incremental);

            var mockBackupStoreObject = new Moq.Mock <ICentralBackupStore>();

            mockBackupStoreObject
            .Setup(store => store.RetrieveScheduledBackupAsync(It.IsAny <Guid>()))
            .Returns(Task.FromResult(incrementalMetadata));

            mockBackupStoreObject
            .Setup(store => store.GetBackupMetadataAsync(null, It.IsAny <Guid>()))
            .Returns(Task.FromResult <IEnumerable <BackupMetadata> >(new[] { backupMetadata, incrementalMetadata, incrementalMetadataTwo }));

            var mockServiceObject = new Moq.Mock <IBackupRestoreServiceOperations>();

            mockServiceObject.Setup(service => service.CentralBackupStore).Returns(mockBackupStoreObject.Object);
            mockServiceObject.Setup(service => service.Context).Returns(Mocks.MockStatefulServiceContextFactory.Default);

            //act
            var result = await BackupRestoreServiceOperations.GetBackupMetadataAsync(mockServiceObject.Object, incrementalMetadataTwo);

            //assert
            Assert.AreEqual(3, result.Count);
            Assert.AreEqual(backupMetadata, result[0]);
            Assert.AreEqual(incrementalMetadata, result[1]);
            Assert.AreEqual(incrementalMetadataTwo, result[2]);
        }
Ejemplo n.º 8
0
 public void Setup()
 {
     _order = new Order();
     _mockNotifier = new Moq.Mock<INotify>();
     _orderProcessor =
         new OrderProcessor(_mockNotifier.Object);
 }
Ejemplo n.º 9
0
        public void TransferFunds()
        {
            //arrange the MockObject
            var logMock = new Moq.Mock <ILogger>();

            //arrange SUT

            var client      = new ClientDummy();
            var source      = new AccountForLogSpy(200, client, logMock.Object);
            var destination = new AccountForLogSpy(150, client, logMock.Object);

            //set mocked logger expectations

            logMock.Setup(d => d.Log("method Log was called with message : Transaction : 100 & 250"));

            //logMock.ExpectedNumberOfCalls(1);

            //act

            source.TransferFunds(destination, 100.00F);

            //assert
            Assert.AreEqual(250.00F, destination.Balance);
            Assert.AreEqual(100.00F, source.Balance);

            //mock object verify

            logMock.Verify(_ => _.Log("method Log was called with message : Transaction : 100 & 250"), Times.Once());
        }
Ejemplo n.º 10
0
 public StepDefinitions()
 {
     var mock = new Moq.Mock<IUserAuthentication>();
     mock.Expect(x => x.IsValidLogin("admin", "password")).Returns(true);
     //mock.Expect(x => x.IsValidLogin(It.IsAny<string>(), It.IsAny<string>())).Returns(false);
     _auth = mock.Object;
 }
Ejemplo n.º 11
0
        public void ParseTasksDeleteTask()
        {
            var mockTaskCreator = new Mock <ITaskCreator>();

            // mock a task which Id is 2
            var mockUpdateTask = new Moq.Mock <ITask>();

            mockUpdateTask.SetupGet(x => x.Id).Returns(2);
            mockTaskCreator.Setup(ct => ct.Creator(It.IsAny <string>()))
            .Returns(mockUpdateTask.Object);
            var target = new TaskManager(
                mockTaskCreator.Object,
                this.mockNetworkClient.Object,
                this.mockExceptionPolicy.Object);

            // this set is not complete, it ignores the content for TaskCreator. execute
            // create first
            var taskxml =
                "<Tasks><Task><Id>2></Id>"
                + "<Action>Create</Action></Task></Tasks>";

            target.ParseTasks(taskxml);
            Assert.AreEqual(target.Tasks.Count, 1);

            // this is for test delete action
            taskxml = "<Tasks><Task><Id>2</Id>"
                      + "<Action>Delete</Action></Task></Tasks>";
            target.ParseTasks(taskxml);
            mockTaskCreator.Verify(
                m => m.Creator(It.IsAny <string>()), Times.Exactly(2));
            Assert.AreEqual(target.Tasks.Count, 0);
        }
        public void Can_pass_realistic_build_arguments_to_script()
        {
            // arrange
            // redirect the console
            var consoleOut = Helpers.Logging.RedirectConsoleOut();


            var emailProvider       = new Moq.Mock <IEmailProvider>();
            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();
            var eventDataProvider   = new Moq.Mock <IEventDataProvider>();

            var args = new Dictionary <string, object>
            {
                { "Arguments", new[] { "build.complete", "123" } },
            };
            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            // act
            engine.RunScript(
                @"TestDataFiles\Scripts\AzureDevOps\alerts\fullscript.py",
                args,
                azureDevOpsProvider.Object,
                emailProvider.Object,
                eventDataProvider.Object);

            // assert

            Assert.AreEqual("Got a known build.complete event type with id 123" + Environment.NewLine, consoleOut.ToString());
        }
Ejemplo n.º 13
0
        public void ClientSideValidationRules_Helper_Passes_ActiveRuleProvider_Output_To_Formatter()
        {
            // Arrange
            var html = new HtmlHelperMocks<object>().HtmlHelper;
            var arbitraryType = typeof (DateTime);
            var ruleProvider = new Moq.Mock<IRulesProvider>();
            var rules = new RuleSet(new[] { "someProperty" }.ToLookup(x => x, x => (Rule)new RequiredRule()));
            ruleProvider.Expect(x => x.GetRulesFromType(arbitraryType)).Returns(rules);
            ActiveRuleProviders.Providers.Clear();
            ActiveRuleProviders.Providers.Add(ruleProvider.Object);

            // Capture params passed to mockFormatter
            var mockFormatter = new Moq.Mock<IValidationConfigFormatter>(MockBehavior.Strict);
            RuleSet passedRules = null;
            Action<RuleSet> callback = x =>
            {
                passedRules = x;
            };
            mockFormatter.Expect(x => x.FormatRules(It.IsAny<RuleSet>()))
                .Callback(callback)
                .Returns("ok");
            ValidationInfo.Formatter = mockFormatter.Object;

            // Act
            var result = html.ClientSideValidationRules(arbitraryType);

            // Assert
            Assert.Equal("ok", result.ToString());
            Assert.Equal(1, passedRules.Keys.Count());
            Assert.Same(rules["someProperty"].Single(), passedRules["someProperty"].First());
        }
        public void Can_use_Dsl_to_find_if_no_parent_work_item()
        {
            // arrange
            // redirect the console
            var consoleOut = Helpers.Logging.RedirectConsoleOut();

            var emailProvider       = new Moq.Mock <IEmailProvider>();
            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();
            var eventDataProvider   = new Moq.Mock <IEventDataProvider>();

            azureDevOpsProvider.Setup(t => t.GetWorkItem(297)).Returns(RestTestData.GetSingleWorkItemByID());
            // don't need to assign a value for the parent call as will return null by default
            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            // act
            engine.RunScript(
                @"TestDataFiles\Scripts\AzureDevOps\api\loadparentwi.py",
                azureDevOpsProvider.Object,
                emailProvider.Object,
                eventDataProvider.Object);

            // assert
            Assert.AreEqual(
                "Work item '309' has no parent" + Environment.NewLine,
                consoleOut.ToString());
        }
        public void Can_use_Dsl_to_retrieve_a_changeset()
        {
            // arrange
            // redirect the console
            var consoleOut = Helpers.Logging.RedirectConsoleOut();

            var emailProvider       = new Moq.Mock <IEmailProvider>();
            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();
            var eventDataProvider   = new Moq.Mock <IEventDataProvider>();

            azureDevOpsProvider.Setup(t => t.GetChangesetDetails(7)).Returns(RestTestData.GetChangeSetDetails());
            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            // act
            engine.RunScript(
                @"TestDataFiles\Scripts\AzureDevOps\api\loadchangeset.py",
                azureDevOpsProvider.Object,
                emailProvider.Object,
                eventDataProvider.Object);

            // assert
            Assert.AreEqual(
                "Changeset '7' has the comment 'Added 2 files to SampleProject' and contains 2 files" + Environment.NewLine,
                consoleOut.ToString());
        }
        public void Can_use_Dsl_to_retrieve_a_work_item()
        {
            // arrange
            // redirect the console
            var consoleOut = Helpers.Logging.RedirectConsoleOut();

            var emailProvider       = new Moq.Mock <IEmailProvider>();
            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();
            var eventDataProvider   = new Moq.Mock <IEventDataProvider>();

            azureDevOpsProvider.Setup(t => t.GetWorkItem(297)).Returns(RestTestData.GetSingleWorkItemByID());
            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            // act
            engine.RunScript(
                @"TestDataFiles\Scripts\AzureDevOps\api\loadwi.py",
                azureDevOpsProvider.Object,
                emailProvider.Object,
                eventDataProvider.Object);

            // assert
            Assert.AreEqual(
                "Work item '309' has the title 'Customer can sign in using their Microsoft Account'" + Environment.NewLine,
                consoleOut.ToString());
        }
        public void Can_use_Dsl_to_get_build_details()
        {
            // arrange
            var consoleOut = Helpers.Logging.RedirectConsoleOut();

            var emailProvider = new Moq.Mock <IEmailProvider>();

            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();

            azureDevOpsProvider.Setup(t => t.GetBuildDetails(It.IsAny <int>())).Returns(RestTestData.GetBuildDetails());
            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            var eventDataProvider = new Moq.Mock <IEventDataProvider>();


            // act
            engine.RunScript(
                @"TestDataFiles\Scripts\AzureDevOps\api\loadbuild.py",
                azureDevOpsProvider.Object,
                emailProvider.Object,
                eventDataProvider.Object);

            // assert
            Assert.AreEqual("Build 'vstfs:///Build/Build/391' has the result 'succeeded'" + Environment.NewLine, consoleOut.ToString());
        }
Ejemplo n.º 18
0
        public void AsteroidHasDifficulty()
        {
            var veldnium = new ItemInfo(ItemCode.Veldnium);
            var itemFactory = new Moq.Mock<IItemFactory>(MockBehavior.Strict);
            itemFactory.Setup(x => x.Build(ItemCode.Veldnium, It.IsAny<uint>()))
                .Returns<ItemCode, uint>((item, quantity) => new Item(veldnium, quantity));

            var mining = new MiningTask(itemFactory.Object) { };
            mining.SetParameters(new MineAsteroidParameters(_ship, _difficultAsteroid));

            var result = mining.Mine();
            Assert.That(result.Success, Is.True);
            Assert.That(result.StatusCode, Is.EqualTo(ShipTask.StatusCode.Pending));
            Assert.That(_difficultAsteroid.AmountRemaining, Is.EqualTo(1000));
            Assert.That(_ship.Tasks, Contains.Item(mining));

            result = mining.Mine();

            Assert.That(result.Success, Is.True);
            Assert.That(result.StatusCode, Is.EqualTo(ShipTask.StatusCode.Success));

            Assert.That(result.Ore.Quantity, Is.EqualTo(2));
            Assert.That(_difficultAsteroid.AmountRemaining, Is.EqualTo(998));
            _ship.Tasks.ShouldNotContain(mining);
        }
        public void Can_use_Dsl_to_update_a_work_item()
        {
            // arrange
            // redirect the console
            var consoleOut = Helpers.Logging.RedirectConsoleOut();

            var emailProvider       = new Moq.Mock <IEmailProvider>();
            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();
            var eventDataProvider   = new Moq.Mock <IEventDataProvider>();

            azureDevOpsProvider.Setup(t => t.CreateWorkItem(
                                          "tp",
                                          "Bug",
                                          new Dictionary <string, object>()
            {
                { "Title", "The Title" },
                { "Estimate", 2 }
            })).Returns(RestTestData.CreateWorkItem());
            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            // act
            engine.RunScript(
                @"TestDataFiles\Scripts\AzureDevOps\api\updatewi.py",
                azureDevOpsProvider.Object,
                emailProvider.Object,
                eventDataProvider.Object);

            // assert
            azureDevOpsProvider.Verify(t => t.UpdateWorkItem(It.IsAny <JObject>()));
        }
Ejemplo n.º 20
0
        public void SetUp()
        {
            var mock = new Moq.Mock<ILocationServices>();
            mock.Setup(x => x.GetExitPosition(It.IsAny<ILocation>())).Returns<ILocation>(l => l.Position.LocalCoordinates);

            _task = new JumpShipTask(mock.Object);
        }
        public void Can_use_Dsl_to_retrieve_a_push()
        {
            // arrange
            // redirect the console
            var consoleOut = Helpers.Logging.RedirectConsoleOut();

            var emailProvider       = new Moq.Mock <IEmailProvider>();
            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();
            var eventDataProvider   = new Moq.Mock <IEventDataProvider>();

            azureDevOpsProvider.Setup(t => t.GetPushDetails("3c4e22ee-6148-45a3-913b-454009dac91d", 73)).Returns(RestTestData.GetPushDetails());
            azureDevOpsProvider.Setup(t => t.GetCommitDetails(It.IsAny <Uri>())).Returns(RestTestData.GetCommitDetails());
            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            // act
            engine.RunScript(
                @"TestDataFiles\Scripts\AzureDevOps\api\loadpush.py",
                azureDevOpsProvider.Object,
                emailProvider.Object,
                eventDataProvider.Object);

            // assert
            Assert.AreEqual(
                "Push '73' contains 2 commits\r\nCommit be67f8871a4d2c75f13a51c1d3c30ac0d74d4ef4\r\nCommit be67f8871a4d2c75f13a51c1d3c30ac0d74d4ef4\r\n",
                consoleOut.ToString());
        }
Ejemplo n.º 22
0
        public void AdvancedSearchAds_SearchThroughAds_CallSearchRepoOnAds()
        {
            // Given
            Category cat = new Category { Id = 1, LabelUrlPart = "cat-url-label", Label = "Label", Type = AdTypeEnum.Ad };

            AdSearchModel model = new AdSearchModel();
            model.CategorySelectedId = 1;
            model.SearchString = "toto";
            model.CitySelectedId = 12;

            IList<SearchAdCache> searchResult = new List<SearchAdCache>();
            searchResult.Add(new SearchAdCache
            {
                Title = "ship",
                City = new City() { Label = "the city" },
                Category = cat
            });

            var repoMock = new Moq.Mock<IRepository>();
            repoMock.Setup(r => r.Get<Category>(cat.Id)).Returns(cat);

            var searchRepoMock = new Moq.Mock<ISearchRepository>();
            searchRepoMock.Setup(r => r.SearchAds(It.Is<String[]>(x => x[0] == "toto"), 12, It.Is<int[]>(x => x[0] == 1))).Returns(searchResult);

            SearchServices service = new SearchServices(repoMock.Object, null, searchRepoMock.Object, null, null, null);

            // When
            AdSearchResultModel result = service.LightSearchAds(model);

            // Then
            Assert.AreEqual(1, result.SearchResultTotalCount);
        }
Ejemplo n.º 23
0
        public void Can_use_Dsl_to_send_templated_email()
        {
            // arrange
            var emailProvider       = new Moq.Mock <IEmailProvider>();
            var azureDevOpsProvider = new Moq.Mock <IAzureDevOpsProvider>();

            azureDevOpsProvider.Setup(t => t.GetWorkItem(99)).Returns(RestTestData.GetSingleWorkItemByID());

            var engine = new AzureDevOpsEventsProcessor.Dsl.DslProcessor();

            var args = new Dictionary <string, object> {
                { "Arguments", new[] { "WorkItemEvent", "99" } },
            };

            // act
            engine.RunScript(
                @".\dsl",
                @"TestDataFiles\Scripts\AzureDevOps\alerts",
                "sendtemplatedemail.py",
                args,
                azureDevOpsProvider.Object,
                emailProvider.Object,
                new Providers.JsonDataProvider(ServiceHookTestData.GetEventJson("workitem.updated")));

            // assert
            emailProvider.Verify(
                e =>
                e.SendEmailAlert(
                    Moq.It.IsAny <IFieldLookupProvider>(),
                    System.IO.Path.Combine(engine.BasePath, @"TestDataFiles\Scripts\AzureDevOps\alerts\EmailTemplate.htm"),
                    true,
                    true));
        }
Ejemplo n.º 24
0
        public void GetExpenses_oneValidExpense_Ok()
        {
            var repoExpense1 = new Domain.Expense
            {
                Amount      = 100,
                Category    = "grocery",
                ExpneseDate = new DateTime(2016, 11, 15),
                ID          = 1,
                Merchant    = "pns"
            };
            var repoExpenses = new List <Domain.Expense>()
            {
                repoExpense1
            };
            var repo = new Moq.Mock <IExpenseRepository>();

            repo.Setup <List <Expense> >(t => t.GetAllExpenses())
            .Returns(repoExpenses);

            var fac = new Moq.Mock <ITransactionFactory>();

            fac.Setup <DisplayExpensesTransaction>(m => m.CreateDisplayExpensesTransaction())
            .Returns(new DisplayExpensesTransaction(repo.Object));

            var sut = new ExpensesController(fac.Object, _logger.Object);

            //act
            var actualResponse = sut.Get();
            var contentResult  = actualResponse as OkNegotiatedContentResult <IEnumerable <ViewModels.Expense> >;

            //assert
            Assert.IsNotNull(contentResult, "Ok-200 status was not returned");
            Assert.IsNotNull(contentResult.Content, "No content was returned");
        }
Ejemplo n.º 25
0
        public OwinServerFixture()
        {
            var list = new List<TodoItem> {
                new TodoItem() { Id = 1, Completed = false, Title = "Test 1" },
                new TodoItem() { Id = 2, Completed = true, Title = "Test 2" }
            };

            ServiceMock = new Moq.Mock<ITodoService>();
            ServiceMock.Setup(x => x.GetAllAsync()).ReturnsAsync(list);

            var notCompleted = list.Where(x => x.Completed == false).ToList();
            ServiceMock.Setup(x => x.ClearCompleted()).ReturnsAsync(notCompleted);

            var newTask = new TodoItem() { Completed = false, Title = "Test 3" };
            ServiceMock.Setup(x => x.AddAsync(It.IsAny<TodoItem>())).ReturnsAsync(newTask);

            const int taskId = 2;
            var existingTask = new TodoItem() { Id = 2, Completed = false, Title = "Test 3" };
            ServiceMock.Setup(x => x.UpdateAsync(taskId, It.IsAny<TodoItem>())).ReturnsAsync(existingTask);
            ServiceMock.Setup(x => x.DeleteAsync(taskId)).ReturnsAsync(true);

            const int missingTaskId = 4;
            ServiceMock.Setup(x => x.UpdateAsync(missingTaskId, existingTask)).ReturnsAsync(null);
            ServiceMock.Setup(x => x.DeleteAsync(missingTaskId)).ReturnsAsync(false);

            TestServer = TestServer.Create(Configuration);
        }
Ejemplo n.º 26
0
        private static IDataService GetDataServiceMock(List<Product> products)
        {
            var dataServiceMock = new Moq.Mock<IDataService>(MockBehavior.Strict);
            dataServiceMock.Setup(s => s.GetProductsByProductCode(It.IsAny<int>())).Returns(products);

            return dataServiceMock.Object;
        }
        public void Test_NormalViewModel()
        {
            ClearAll();

            IMvxViewModel outViewModel = new Test2ViewModel();

            var mockLocator = new Mock<IMvxViewModelLocator>();
            mockLocator.Setup(
                m => m.Load(It.IsAny<Type>(), It.IsAny<IMvxBundle>(), It.IsAny<IMvxBundle>()))
                       .Returns(() => outViewModel);

            var mockCollection = new Moq.Mock<IMvxViewModelLocatorCollection>();
            mockCollection.Setup(m => m.FindViewModelLocator(It.IsAny<MvxViewModelRequest>()))
                          .Returns(() => mockLocator.Object);

            Ioc.RegisterSingleton(mockCollection.Object);

            var parameters = new Dictionary<string, string> { { "foo", "bar" } };
            var request = new MvxViewModelRequest<Test2ViewModel>(new MvxBundle(parameters), null,
                                                                  MvxRequestedBy.UserAction);
            var state = new MvxBundle();
            var loader = new MvxViewModelLoader();
            var viewModel = loader.LoadViewModel(request, state);

            Assert.AreSame(outViewModel, viewModel);
            Assert.AreEqual(MvxRequestedBy.UserAction, viewModel.RequestedBy);
        }
Ejemplo n.º 28
0
        public void WhenAPageWithResultsIsReturnedTheResultsShouldBeExtracted()
        {
            // ARRANGE
            List<QUnitTest> expectedResult = new List<QUnitTest>();
            expectedResult.Add(new QUnitTest { TestName = "IE browser should call IE branch", Result = "pass", Message = "", FileName = "" });
            expectedResult.Add(new QUnitTest { TestName = "Firefox browser should call its branch", Result = "fail", Message = "Register Css For Firefox is called Once", FileName = "" });
            var mockWebResponse = new Mock<WebResponse>();

            var embeddedResourceHelper = new EmbeddedResourceHelper(
                Assembly.GetExecutingAssembly(),
                FullDataResource("QUnitResults.htm"),
                "QUnitResults.htm"
                );

            var testUrl = String.Format("file://{0}", embeddedResourceHelper.FullPath);

            Moq.Mock<IBrowser> mockBrowser = new Moq.Mock<IBrowser>();

            // ACT
            var sut = new QUnitParserHtmlUnit(5000,new HtmlUnitBrowser());
            var result = sut.GetQUnitTestResults(testUrl);

            // ASSERT
            var resultEnumerator = result.GetEnumerator();
            var expectedItem = 0;
            while (resultEnumerator.MoveNext())
            {
                Assert.That(resultEnumerator.Current.Result, Is.EqualTo(expectedResult[expectedItem].Result));
                Assert.That(resultEnumerator.Current.Message, Is.EqualTo(expectedResult[expectedItem].Message));
                Assert.That(resultEnumerator.Current.FileName, Is.EqualTo(expectedResult[expectedItem].FileName));
                Assert.That(resultEnumerator.Current.InitializationException, Is.EqualTo(expectedResult[expectedItem].InitializationException));
                Assert.That(resultEnumerator.Current.TestName, Is.EqualTo(expectedResult[expectedItem].TestName));
                expectedItem++;
            }
        }
Ejemplo n.º 29
0
        public void ReadsCorrectly()
        {
            // arrange
            var converter = new EnumConverter();
            var reader1   = new Moq.Mock <JsonReader>();

            reader1.SetupGet(x => x.Value).Returns(null);
            var reader2 = new Moq.Mock <JsonReader>();

            reader2.SetupGet(x => x.Value).Returns("0");
            var reader3 = new Moq.Mock <JsonReader>();

            reader3.SetupGet(x => x.Value).Returns("1");

            // act
            var object1 = converter.ReadJson(reader1.Object, typeof(System.ConsoleColor), null, null);
            var object2 = converter.ReadJson(reader1.Object, typeof(System.ConsoleColor?), null, null);
            var object3 = converter.ReadJson(reader2.Object, typeof(System.ConsoleColor), null, null);
            var object4 = converter.ReadJson(reader3.Object, typeof(System.ConsoleColor), null, null);

            // assert
            Assert.IsNull(object1);
            Assert.IsNull(object2);
            Assert.AreEqual(System.ConsoleColor.Black, (System.ConsoleColor)object3);
            Assert.AreEqual(System.ConsoleColor.DarkBlue, (System.ConsoleColor)object4);
        }
Ejemplo n.º 30
0
        internal void ElapsedEventTick_ReturnsNewestTrack()
        {
            var oldTrack = new Track()
            {
                Artist          = "Artist",
                Title           = "Title",
                TitleExtended   = "Remastered",
                Playing         = true,
                CurrentPosition = 240,
                Length          = 240,
            };
            var newestTrack = new Track()
            {
                Artist        = "Artist",
                Title         = "Title",
                TitleExtended = "Live",
                Playing       = true,
                Length        = 240,
            };

            var spotifyStatusMock = new Moq.Mock <ISpotifyStatus>();

            spotifyStatusMock.Setup(x => x.CurrentTrack).Returns(newestTrack);
            spotifyStatusMock.Setup(x => x.GetTrack()).ReturnsAsync(newestTrack);

            var spotifyProcessMock = new Moq.Mock <ISpotifyProcess>();

            spotifyProcessMock.Setup(x => x.GetSpotifyStatus()).ReturnsAsync(spotifyStatusMock.Object);

            var spotifyHandler = new SpotifyHandler(spotifyProcessMock.Object)
            {
                ListenForEvents = true
            };

            spotifyHandler.Track = oldTrack;

            Track eventNewTrack = null;
            Track eventOldTrack = null;

            spotifyHandler.OnTrackChange += delegate(object sender, TrackChangeEventArgs e)
            {
                eventOldTrack = e.OldTrack;
                eventNewTrack = e.NewTrack;
                Assert.Equal(oldTrack, eventOldTrack);
                Assert.Equal(newestTrack, eventNewTrack);
            };

            int?eventTrackTime = null;

            spotifyHandler.OnTrackTimeChange += delegate(object sender, TrackTimeChangeEventArgs e)
            {
                eventTrackTime = e.TrackTime;
                Assert.Equal(0, eventTrackTime);
            };

            spotifyHandler.ElapsedEventTick(new object { }, new EventArgs() as System.Timers.ElapsedEventArgs);

            spotifyProcessMock.Verify(n => n.GetSpotifyStatus(), Times.Once);
        }
		public void shouldBeAbleToReportWarnings() {
			var avegaContactServiceMock = new Moq.Mock<IAvegaContactService>();

			var avetaContactService = avegaContactServiceMock.Object;
			avetaContactService.Warning += (sender, ev) => {
				Console.WriteLine(ev.Message);
			};
		}
Ejemplo n.º 32
0
 internal Mock(MockBehavior behavior, Moq.Mock <TMock> baseMessageContext) : base(behavior)
 {
     if (baseMessageContext == null)
     {
         throw new ArgumentNullException("baseMessageContext");
     }
     _baseMessageContext = baseMessageContext;
 }
Ejemplo n.º 33
0
        public async Task dado_uma_lista_de_receitas_do_repository_elas_devem_ser_retornadas_em_ordem_alfabetica()
        {
            var repository = new Moq.Mock <IRepository>();

            repository.Setup(a => a.List(It.IsAny <int>())).Returns(new List <Recipe>());
            repository.Setup(a => a.List(2)).Returns(new List <Recipe>());
            repository.Setup(a => a.List(3)).Returns(new List <Recipe>());
        }
Ejemplo n.º 34
0
        public async Task RegisterTest()
        {
            Mock <UserGrain> user = new Moq.Mock <UserGrain>(Moq.MockBehavior.Loose);
            Guid             g    = Guid.NewGuid();

            user.SetupGet(u => u.Email).Returns($"avi.kessler+{g.ToString("N")}@gmail.com");
            Assert.IsTrue(await user.Object.Register(g.ToString("N")));
        }
Ejemplo n.º 35
0
        private Moq.Mock <IBusinessEngineInput> BuildBusinessEngineInput(string HL7MessageFile)
        {
            var    Input      = new Moq.Mock <IBusinessEngineInput>();
            string HL7Message = GetTestMessage(HL7MessageFile);

            Input.Setup(x => x.HL7V2Message).Returns(HL7Message);
            return(Input);
        }
Ejemplo n.º 36
0
        static IProductsRepository MockProductsRepository(params Product[] prods)
        {
            var mockProductsRepos = new Moq.Mock <IProductsRepository>();

            mockProductsRepos.Setup(x => x.Products).Returns(prods.AsQueryable());

            return(mockProductsRepos.Object);
        }
 private void TestGood1()
 {
     var mock1 = new Moq.Mock <IMyService>();
     var mock2 = new Moq.Mock <IMyService>(MockBehavior.Default);
     var mock3 = new Mock <IMyService>(MockBehavior.Strict);
     var mock4 = new Mock <NoConstructorArgumentsForInterfaceMock_1.IMyService>(MockBehavior.Loose);
     var mock5 = new Moq.Mock <NoConstructorArgumentsForInterfaceMock_1.IMyService>(MockBehavior.Default);
 }
        /// <summary>
        /// Creates a real instance but use Moq to intercept calls to virtual methods
        /// Allows who the call is owned by to bet set
        /// </summary>
        /// <param name="assignedTo">Who the call is assigned to</param>
        /// <returns>The fake instance</returns>
        internal static Mock <AzureDevOpsFieldLookupProvider> MockedAzureDevOpsFieldLookupProvider(string assignedTo)
        {
            var mock = new Moq.Mock <AzureDevOpsFieldLookupProvider>();

            mock.Setup(f => f.LookupWorkItemFieldValue("System.AssignedTo")).Returns(assignedTo);
            mock.Setup(f => f.GetUserIdFromDisplayName(assignedTo)).Returns(assignedTo);
            return(mock);
        }
Ejemplo n.º 39
0
 private void GoalSetup()
 {
     AutoMapper.Mapper.CreateMap<ContestEventGoal, ContestEventGoalViewModel>()
         .ForMember(dest => dest.Result, opt => opt.ResolveUsing<GoalDataResolver>());
     profileRepositoryMock = new Moq.Mock<IProfileRepository>();
     profileRepositoryMock.Setup(t => t.RetrieveGoals()).Returns(goals);
     controller = new GoalController(profileRepositoryMock.Object);
 }
Ejemplo n.º 40
0
        private IPricingRepository GetPricingRepositoryMock(IEnumerable <PriceEntity> prices)
        {
            var mock = new Moq.Mock <IPricingRepository>();

            mock.Setup(foo => foo.Prices).Returns(prices.AsQueryable());

            return(mock.Object);
        }
Ejemplo n.º 41
0
        static IProductsRepository MockProductsRepository(params Product[] prods)
        {
            var mockProductsRepos = new Moq.Mock<IProductsRepository>();

            mockProductsRepos.Setup(x => x.Products).Returns(prods.AsQueryable());

            return mockProductsRepos.Object;
        }
Ejemplo n.º 42
0
        public static Mock <IPromptCaller <T> > MockDialog <T>(string id = null)
        {
            var dialog = new Moq.Mock <IPromptCaller <T> >(MockBehavior.Loose);

            id = id ?? NewID();
            dialog.Setup(d => d.ToString()).Returns(id);
            return(dialog);
        }
Ejemplo n.º 43
0
        public void DoesNotDisposeCacheStoreIfPassedToIt()
        {
            var mock    = new Moq.Mock <ICacheStore>(MockBehavior.Strict);
            var handler = new CachingHandler(mock.Object);

            handler.Dispose();
            mock.Verify();
        }
Ejemplo n.º 44
0
        [TestCase(1, "2020-14-01")] //One day before - ON
        public void DaysLeftAsOfShouldWork(int a, string b)
        {
            var      logMock = new Moq.Mock <IEventLogger>();
            var      my_task = MyTaskFactory.Instance.CreateTask("test_description", DateTime.Parse("2020-15-01"), "test_project", "test_owner", "test_asignee", MyTask.Convert("InProgress"), "test_review", logMock.Object);
            TimeSpan ts      = new TimeSpan(a, 0, 0, 0);

            Assert.AreEqual(ts, my_task.DaysLeftAsOf(DateTime.Parse(b)));
        }
Ejemplo n.º 45
0
        public void Init()

        {
            _machine    = new Moq.Mock <IMachine>();
            _pcbManager = new Moq.Mock <IPCBManager>();
            _pointStabilizationFilter = new Moq.Mock <IPointStabilizationFilter>();
            _boardAlignmentManager    = new BoardAlignmentManager(_machine.Object, new FakeLogger(), _pcbManager.Object, _pointStabilizationFilter.Object);
        }
Ejemplo n.º 46
0
        public void IncludesMessageAboutNoActualCallsInFailureMessage()
        {
            var mock = new Moq.Mock <IFoo>();

            MockException mex = Assert.Throws <MockException>(() => mock.Verify(f => f.Execute("pong")));

            Assert.Contains(Environment.NewLine + "No invocations performed.", mex.Message);
        }
Ejemplo n.º 47
0
        public void AddTaskQueue()
        {
            var mock = new Moq.Mock<ITask>();

            var queue = new TaskQueue();
            queue.Add(mock.Object);

            Assert.That(queue.Count, Is.EqualTo(1));
        }
		public static Mock<IPublishedContent> Content(string name, IEnumerable<IPublishedContent> children)
		{
			var mockedItem = new Moq.Mock<IPublishedContent>();
			mockedItem.SetupGet(m => m.Id).Returns(1);
			mockedItem.SetupGet(m => m.Name).Returns(name);
			mockedItem.SetupGet(m => m.Children).Returns(children);

			return mockedItem;
		}
 IScriptModuleRepository GetMockedScriptModuleRepositoryForDependencyGraph(IEnumerable<string> dependencyGraph, out ModuleInfo mainModule)
 {
     var moduleRepo = new Moq.Mock<IScriptModuleRepository>();
     foreach (var moduleInfo in GetModuleArrayFromDependencyGraph(dependencyGraph, out mainModule))
     {
         moduleRepo.Setup((repo) => repo.GetModule(moduleInfo.Name)).Returns(moduleInfo);
     }
     return moduleRepo.Object;
 }
		public void shouldHaveGetAll() {
			var avegaContactRepositoryMock = new Moq.Mock<IAvegaClientRepository>();

			avegaContactRepositoryMock.Setup(x=>x.GetAll())
				.Returns(new List<AvegaContact>());

			IAvegaClientRepository avegaContactRepository = avegaContactRepositoryMock.Object;
			avegaContactRepository.GetAll();
		}
		public void shouldBeAbleToValidateAuthentication() {

			var avegaClientRepositoryMock = new Moq.Mock<IAvegaClientRepository>();
			avegaClientRepositoryMock.Setup(x => x.IsAuthenticationValid).Returns(true);


			Assert.IsTrue(avegaClientRepositoryMock.Object.IsAuthenticationValid);
				
		}
Ejemplo n.º 52
0
        public void CanBuild()
        {
            var itemFactory = new Moq.Mock<IItemFactory>(MockBehavior.Strict);
            var expected = TestItems.BuildItem(_universe.BluePrint.Code, _universe.BluePrint.TargetQuantity);
            itemFactory.Setup(f => f.Build(_universe.BluePrint.Code, _universe.BluePrint.TargetQuantity)).Returns(expected);

            var item = BluePrint.Build(itemFactory.Object);
            item.ShouldBeSameAs(expected);
        }
		public void shouldBeAbleToGetAllAvegaContact() {
			var avegaContactServiceMock = new Moq.Mock<IAvegaContactService>();
			avegaContactServiceMock.Setup(x => x.GetAllContacts())
				.Returns(new List<AvegaContact>());

			var avetaContactService = avegaContactServiceMock.Object;
			avetaContactService.GetAllContacts();

			avegaContactServiceMock.Verify();
		}
        public void OpenTest()
        {
            var mock = new Moq.Mock<IMyDriver>();
            var client = new MyWork.MyConnection(new[] {mock.Object});
            mock.Setup(driver => driver.Connect());

            client.Open();

            mock.VerifyAll();
        }
Ejemplo n.º 55
0
        public void AggregateBus_RegisteredAggregateCachesShouldContainAtLeastTheConfiguredValue()
        {
            var eventBus = new Moq.Mock<IEventBus>();
            eventBus.Setup(e => e.Subscribe<AggregateCacheCleared>(Moq.It.IsAny<Func<AggregateCacheCleared, Task>>())).Verifiable();
            var aggregateCache = new Moq.Mock<IAggregateCache>();

            AggregateBus.Instance.Configure(eventBus.Object, aggregateCache.Object);

            AggregateBus.Instance.RegisteredAggregateCaches.FirstOrDefault().Should().Be(aggregateCache.Object);
        }
Ejemplo n.º 56
0
        public void CancelAsync()
        {
            var element = new ImportNetworkElement();
            var mockMyFx = new Moq.Mock<IImportNetworkFx>();

            mockMyFx.Setup(m => m.CancelAsync());

            element.Fx = mockMyFx.Object;
            element.Cancel();
            mockMyFx.Verify(m => m.CancelAsync(), Times.Exactly(1));
        }
        public void ContentManagerPropertyIsSet()
        {
            var contentManager = _container.Resolve<IContentManager>();
            var query = contentManager.Query();
            Assert.That(query.ContentManager, Is.SameAs(contentManager));

            var mockManager = new Moq.Mock<IContentManager>().Object;
            var anotherQuery = _container.Resolve<IContentQuery>(TypedParameter.From(mockManager));
            Assert.That(anotherQuery, Is.Not.SameAs(query));
            Assert.That(anotherQuery.ContentManager, Is.SameAs(mockManager));
        }
Ejemplo n.º 58
0
        public void When()
        {
            var mock = new Moq.Mock<ITextInstructionFactory>();

            mock.Setup(
                m => m.CreateInstruction(It.IsAny<string>()))
                .Returns((string s) => new StubInstruction(s));

            _stringReader = new StringReader(StreamText);
            Instructions = new InstructionReader(_stringReader, mock.Object);
        }
Ejemplo n.º 59
0
 public void GivenIHaveARunningMonkeyTalkRemoteAtLocation(string location)
 {
     if (location == "mock")
     {
         _mock = new Moq.Mock<IChimpRemote>();
     }
     else
     {
         chimpRemoteDevice = new ChimpRemote(location, string.Empty); //string.Empty should be deviceIp from Devs config file.
     }
     if (_payload == null) _payload = new MonkeyTalkWirePayload();
 }
        public void ReadTransactionsFromFile_Valid_ObserverNeverCalled()
        {
            var mockObserver = new Moq.Mock<Observer>();
            List<Observer> ol = new List<Observer>();
            ol.Add(mockObserver.Object);
            List<Product> listOfProducts = new List<Product>();
            TransactionManager tm = new TransactionManager(ol, listOfProducts);

            tm.ReadTransactionsFromFile(new StreamReader(@"C:\Users\vbhujan\Documents\Cart.txt"));

            mockObserver.Verify(o => o.update(), Times.Never);
        }