Example #1
0
        public void CalculateFrequencyTest()
        {
            var view = new Mock<IMainGameView>();

            var controller = new MainGameController(view.Object);
            controller.LoadKeysResources(TestKeyFileResource);

            view.Setup(x => x.PlaySound(It.Is<int>(f => f == 110), 100));
            controller.ProcessKey(Keys.Q); //key#0
            view.VerifyAll();

            view.Reset();
            view.Setup(x => x.PlaySound(It.Is<int>(f => f == 117), 100));
            controller.ProcessKey(Keys.W); //key#0
            view.VerifyAll();

            view.Reset();
            view.Setup(x => x.PlaySound(It.Is<int>(f => f == 175), 100));
            controller.ProcessKey(Keys.O); //key#8
            view.VerifyAll();

            view.Reset();
            view.Setup(x => x.PlaySound(It.Is<int>(f => f == 185), 100));
            controller.ProcessKey(Keys.P); //key#9
            view.VerifyAll();
        }
        public void Test_ExecuteScripts_TwoFileContent()
        {
            const bool expectedResult = true;
            const string fileContent = @"create table BackendUser (BackendUserId int, Username nvarchar(30))
                                  ;
                                  insert into BackendUser values(1, ""I must go home.""))
                                  ;";

            var dbConnectionMock = new Mock<IDbConnection>();
            var databaseMock = new Mock<IDatabase>();
            var dbCommandMock = new Mock<IDbCommand>();

            databaseMock.Setup(t => t.GetDbConnection()).Returns(dbConnectionMock.Object);
            databaseMock.Setup(t => t.GetDbCommand()).Returns(dbCommandMock.Object);

            dbConnectionMock.Setup(t => t.Open());
            dbCommandMock.Setup(t => t.ExecuteNonQuery());

            IDbProvider provider = new FireBirdDbProvider(databaseMock.Object);
            var actualResult = provider.ExecuteScript(fileContent);

            dbCommandMock.VerifyAll();
            databaseMock.VerifyAll();
            dbCommandMock.VerifyAll();

            Assert.Equal(expectedResult, actualResult);
        }
        public void Test_ExecuteScripts_TwoFileContent_WithGo()
        {
            const string fileContent = @"create table BackendUser (BackendUserId int, Username nvarchar(30))
                                  go
                                  create table Company (CompanyId int, Name nvarchar(30))
                                 go";
            const bool expectedResult = true;

            var dbConnectionMock = new Mock<IDbConnection>();
            var databaseMock = new Mock<IDatabase>();
            var dbCommandMock = new Mock<IDbCommand>();

            databaseMock.Setup(t => t.GetDbConnection()).Returns(dbConnectionMock.Object);
            databaseMock.Setup(t => t.GetDbCommand()).Returns(dbCommandMock.Object);

            dbConnectionMock.Setup(t => t.Open());
            dbCommandMock.Setup(t => t.ExecuteNonQuery());

            IDbProvider provider = new MsSqlDbProvider(databaseMock.Object);
            var actualResult = provider.ExecuteScript(fileContent);

            dbCommandMock.VerifyAll();
            databaseMock.VerifyAll();
            dbCommandMock.VerifyAll();

            Assert.Equal(expectedResult, actualResult);
        }
		public void CreatesMockForAccessedPropertyWithSetterWithValue()
		{
			var mock = new Mock<IFoo>();

			mock.SetupSet(m => m.Bar.Value = 5);

			Assert.NotNull(mock.Object.Bar);
			Assert.Throws<MockVerificationException>(() => mock.VerifyAll());

			mock.Object.Bar.Value = 5;

			mock.VerifyAll();
		}
        public async Task EditCommentTest(
            EditCommentMode mode,
            string fileExtension,
            string commentStart,
            string commentEnd = null)
        {
            // Arrange
            string commentName = "CommentName";
            string filePath = @"C:\Project\File" + fileExtension;
            Mock<IFileSystemService> fileSystemServiceMock = new Mock<IFileSystemService>(MockBehavior.Strict);
            fileSystemServiceMock
                .Setup(x => x.FileExists(It.Is<string>(y => string.Equals(y, filePath))))
                .Returns(true);
            fileSystemServiceMock
                .Setup(x => x.FileReadAllLines(It.Is<string>(y => string.Equals(y, filePath))))
                .Returns(Task.FromResult(GetInputLines(commentName, commentStart, commentEnd)));
            fileSystemServiceMock
                .Setup(x => x.FileWriteAllLines(
                    It.Is<string>(y => string.Equals(y, filePath)),
                    It.Is<IEnumerable<string>>(y => Enumerable.SequenceEqual(y, GetOutputLines(mode, commentStart, commentEnd)))))
                .Returns(Task.FromResult<object>(null));
            IProjectService projectService = new ProjectService(fileSystemServiceMock.Object, @"C:\Project\Project.xproj");

            // Act
            await projectService.EditComment(commentName, mode, "File" + fileExtension);

            // Assert
            fileSystemServiceMock.VerifyAll();
        }
        public void AddPostValidModel_ReturnsRedirect()
        {
            var volunteerFake = new Volunteer
                                    {
                                        Id = Guid.NewGuid(),
                                    };

            var recipientFake = new Recipient
                                    {
                                        Active = true,
                                        FirstName = "Dan",
                                        Id = Guid.NewGuid(),
                                    };

            var dataServiceMock = new Mock<IDataService<Recipient>>();
            dataServiceMock.Setup(d => d.Insert(It.IsAny<Recipient>(), It.IsAny<Guid>())).Verifiable();

            var formsAuthenticationServiceMock = new Mock<IFormsAuthenticationService>();
            formsAuthenticationServiceMock.Setup(f => f.GetVolunteerID(null))
                .Returns(volunteerFake.Id);

            var controller = new RecipientController(dataServiceMock.Object,
                                                     new Mock<IDataService<Volunteer>>().Object,
                                                     formsAuthenticationServiceMock.Object);

            ActionResult result = controller.Add(recipientFake);

            dataServiceMock.VerifyAll();

            Assert.IsInstanceOf(typeof (RedirectToRouteResult), result);
        }
        public void Given_that_request_is_valid_When_mark_hazard_as_deleted_Then_should_call_correct_methods()
        {
            //Given
            var target = CreateNonEmployeeervice();

            var hazard = new Mock<Hazard>();
            hazard.Setup(x => x.MarkForDelete(_user.Object));

           

            var request = new MarkCompanyDefaultAsDeletedRequest(1, 2, Guid.NewGuid());

            _userRepository
              .Setup(x => x.GetByIdAndCompanyId(request.UserId, request.CompanyId))
              .Returns(_user.Object);

            _repo
                .Setup(x => x.GetByIdAndCompanyId(request.CompanyDefaultId, request.CompanyId))
                .Returns(hazard.Object);


            //When
            target.MarkHazardAsDeleted(request);

            //Then
            hazard.VerifyAll();
            _repo.Verify(x => x.SaveOrUpdate(It.IsAny<Hazard>()));
        }
        public void RepositoryDecoratorBase_Delegate_Calls_To_Surrogate()
        {
            Mock<IRepository<Product>> realRepo = new Mock<IRepository<Product>>();

            realRepo.Setup(rr => rr.AsQueryable()).Returns(new List<Product>{new Product()}.AsQueryable);
            realRepo.Setup(rr => rr.Delete(It.IsAny<Product>()));
            realRepo.Setup(rr => rr.Find(It.IsAny<Expression<Func<Product, bool>>>()));
            realRepo.Setup(rr => rr.GetAll());
            realRepo.Setup(rr => rr.Insert(It.IsAny<Product>()));
            realRepo.Setup(rr => rr.Single(It.IsAny<Expression<Func<Product, bool>>>()));
            realRepo.Setup(rr => rr.Update(It.IsAny<Product>()));

            Mock<RepositoryDecoratorBase<Product>> deco = new Mock<RepositoryDecoratorBase<Product>>(realRepo.Object)
                                                              {CallBase = true};

            deco.Object.AsQueryable();
            deco.Object.Delete(new Product());
            deco.Object.Find(p => p.Id > 0);
            deco.Object.GetAll();
            deco.Object.Insert(new Product());
            deco.Object.Single(p => p.Id > 0);
            deco.Object.Update(new Product());

            realRepo.VerifyAll();
        }
Example #9
0
		public void ReturnsNullValueIfNullFunc()
		{
			var mock = new Mock<IFoo>();
			mock.Setup(foo => foo.Execute("Whatever")).Returns((Func<string>)null);
			Assert.Null(mock.Object.Execute("Whatever"));
			mock.VerifyAll();
		}
        public async Task OnValidatePrincipalTestSuccess(bool isPersistent)
        {
            var user = new TestUser("test");
            var userManager = MockHelpers.MockUserManager<TestUser>();
            var claimsManager = new Mock<IUserClaimsPrincipalFactory<TestUser>>();
            var identityOptions = new IdentityOptions { SecurityStampValidationInterval = TimeSpan.Zero };
            var options = new Mock<IOptions<IdentityOptions>>();
            options.Setup(a => a.Options).Returns(identityOptions);
            var httpContext = new Mock<HttpContext>();
            var contextAccessor = new Mock<IHttpContextAccessor>();
            contextAccessor.Setup(a => a.HttpContext).Returns(httpContext.Object);
            var signInManager = new Mock<SignInManager<TestUser>>(userManager.Object,
                contextAccessor.Object, claimsManager.Object, options.Object, null);
            signInManager.Setup(s => s.ValidateSecurityStampAsync(It.IsAny<ClaimsPrincipal>(), user.Id)).ReturnsAsync(user).Verifiable();
            signInManager.Setup(s => s.SignInAsync(user, isPersistent, null)).Returns(Task.FromResult(0)).Verifiable();
            var services = new ServiceCollection();
            services.AddInstance(options.Object);
            services.AddInstance(signInManager.Object);
            services.AddInstance<ISecurityStampValidator>(new SecurityStampValidator<TestUser>());
            httpContext.Setup(c => c.RequestServices).Returns(services.BuildServiceProvider());
            var id = new ClaimsIdentity(IdentityOptions.ApplicationCookieAuthenticationScheme);
            id.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));

            var ticket = new AuthenticationTicket(new ClaimsPrincipal(id), 
                new AuthenticationProperties { IssuedUtc = DateTimeOffset.UtcNow, IsPersistent = isPersistent }, 
                IdentityOptions.ApplicationCookieAuthenticationScheme);
            var context = new CookieValidatePrincipalContext(httpContext.Object, ticket, new CookieAuthenticationOptions());
            Assert.NotNull(context.Properties);
            Assert.NotNull(context.Options);
            Assert.NotNull(context.Principal);
            await
                SecurityStampValidator.ValidatePrincipalAsync(context);
            Assert.NotNull(context.Principal);
            signInManager.VerifyAll();
        }
        public void op_Verify_IRepository()
        {
            var key = AlphaDecimal.Random();

            var obj = new RepositoryMatchKey<RandomObject>
                          {
                              Record1 =
                                  {
                                      Key = key
                                  }
                          };

            var repository = new Mock<IRepository<RandomObject>>();
            repository
                .Setup(x => x.Insert(obj.Record1))
                .Returns(obj.Record1)
                .Verifiable();
            repository
                .Setup(x => x.Match(key, obj.Record1.Etag))
                .Returns(true)
                .Verifiable();

            obj.Verify(repository.Object);

            repository.VerifyAll();
        }
        public void Add_ValidModelLicenseTypeWithResultPost_ReturnsRedirect()
        {
            var computerFake = new Computer
                                   {
                                       LicenseType = "WinXP",
                                   };

            var computerDataService = new Mock<IDataService<Computer>>();
            computerDataService.Setup(c => c.Insert(It.IsAny<Computer>(), It.IsAny<Guid>())).Verifiable();

            var windowsLicenseDataServiceMock = new Mock<IDataService<WindowsLicense>>();
            windowsLicenseDataServiceMock.Setup(w => w.SelectOne(It.IsAny<Expression<Func<WindowsLicense, bool>>>()))
                .Returns(new WindowsLicense
                             {
                                 Id = "123456",
                                 LicenseType = computerFake.LicenseType,
                             });

            var controller = new ComputerController(computerDataService.Object,
                                                    new Mock<IFormsAuthenticationService>().Object,
                                                    windowsLicenseDataServiceMock.Object,
                                                    new Mock<IDataService<Volunteer>>().Object,
                                                    new Mock<IDataService<Recipient>>().Object);

            ActionResult result = controller.Add(computerFake);

            Assert.IsInstanceOf<RedirectToRouteResult>(result);
            computerDataService.VerifyAll();
        }
        public void ListAll_PerformsCorrectRequest()
        {
            //Setup
            var request = new CategoriesStub("DevKey", "api.careerbuilder.com", "", "");

            //Mock crap
            var response = new RestResponse<List<Category>> {Data = new List<Category>()};

            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("CountryCode", "NL"));
            restReq.SetupSet(x => x.RootElement = "Categories");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/categories");
            restClient.Setup(x => x.Execute<List<Category>>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assert
            List<Category> cats = request.WhereCountryCode(CountryCode.NL).ListAll();
            Assert.IsTrue(cats.Count == 0);
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
            public void ShouldBeAbleToPullExistingInfoFromCache()
            {
                var monitorConfig = new MonitorConfig { Name = "Test" };
                var reduceLevels = new List<ReduceLevel>();

                var connection = new Mock<IDbConnection>();
                var connectionInstance = connection.Object;

                var storageCommands = new Mock<IStorageCommands>();
                storageCommands.Setup(x => x.CreateConfigAndReduceLevels(monitorConfig, reduceLevels, connectionInstance));

                var setupSystemTables = new Mock<ISetupSystemTables>();
                setupSystemTables.Setup(x => x.ValidateAndCreateDataTables(connectionInstance)).Verifiable();

                var monitorConfigsDictionary = new ConcurrentDictionary<string, MonitorConfig>();

                var cache = new Mock<IDataCache>();
                cache.SetupGet(x => x.MonitorConfigs).Returns(monitorConfigsDictionary).Verifiable();

                var storageFactory = new Mock<IStorageFactory>();
                storageFactory.Setup(x => x.CreateConnection()).Returns(connectionInstance).Verifiable();

                var settings = BuildSettings();

                var defaults = new SetupMonitorConfig(storageCommands.Object, setupSystemTables.Object, cache.Object, storageFactory.Object, settings.Object);
                defaults.CreateDefaultReduceLevels(monitorConfig, reduceLevels);

                Assert.Equal(1, monitorConfigsDictionary.Count);
                Assert.True(monitorConfigsDictionary.ContainsKey("Test"));

                storageCommands.VerifyAll();
                setupSystemTables.VerifyAll();
                storageFactory.VerifyAll();
                cache.VerifyAll();
            }
        public void TestExecuteWhenPageIsFoundAndUrlMatchesReturnsSuccess()
        {
            var page = new Mock<IPage>(MockBehavior.Strict);

            var pageMapper = new Mock<IPageMapper>(MockBehavior.Strict);
            pageMapper.Setup(p => p.GetTypeFromName("SamplePage")).Returns(typeof(SamplePage));

            var browser = new Mock<IBrowser>(MockBehavior.Strict);
            browser.Setup(b => b.Page(typeof(SamplePage))).Returns(page.Object);
            browser.Setup(b => b.EnsureOnPage(page.Object));

            var logger = new Mock<ILogger>();

            var action = new WaitForPageAction(pageMapper.Object, browser.Object, logger.Object);
            var context = new WaitForPageAction.WaitForPageActionContext("SamplePage", TimeSpan.FromSeconds(1));

            var result = action.Execute(context);

            Assert.AreEqual(true, result.Success);
            Assert.AreSame(page.Object, result.Result);

            pageMapper.VerifyAll();
            browser.VerifyAll();
            page.VerifyAll();
        }
        public void AssociationSetDiscoveryConvention_AddsBindingForBaseAndDerivedNavigationProperties()
        {
            // Arrange
            ODataModelBuilder builder = new ODataModelBuilder();

            EntityTypeConfiguration vehicle = builder.AddEntity(typeof(Vehicle));

            EntityTypeConfiguration car = builder.AddEntity(typeof(Car)).DerivesFrom(vehicle);
            NavigationPropertyConfiguration carNavigationProperty = car.AddNavigationProperty(typeof(Car).GetProperty("Manufacturer"), EdmMultiplicity.ZeroOrOne);

            EntityTypeConfiguration motorcycle = builder.AddEntity(typeof(Motorcycle)).DerivesFrom(vehicle);
            NavigationPropertyConfiguration motorcycleNavigationProperty = motorcycle.AddNavigationProperty(typeof(Motorcycle).GetProperty("Manufacturer"), EdmMultiplicity.ZeroOrOne);

            EntityTypeConfiguration manufacturer = builder.AddEntity(typeof(Manufacturer));
            EntityTypeConfiguration motorcycleManufacturer = builder.AddEntity(typeof(MotorcycleManufacturer)).DerivesFrom(manufacturer);
            EntityTypeConfiguration carManufacturer = builder.AddEntity(typeof(CarManufacturer)).DerivesFrom(manufacturer);

            EntitySetConfiguration manufacturers = builder.AddEntitySet("manufacturers", manufacturer);


            Mock<EntitySetConfiguration> entitySet = new Mock<EntitySetConfiguration>(MockBehavior.Strict);
            entitySet.Setup(v => v.EntityType).Returns(vehicle);
            entitySet.Setup(v => v.AddBinding(motorcycleNavigationProperty, manufacturers)).Returns<NavigationPropertyConfiguration>(null);
            entitySet.Setup(v => v.AddBinding(carNavigationProperty, manufacturers)).Returns<NavigationPropertyConfiguration>(null);

            // Act
            _convention.Apply(entitySet.Object, builder);

            // Assert
            entitySet.VerifyAll();
        }
        public void TestAccessUsingBasicAuthentication()
        {
            var permissions = new Mock<AbstractSystemPermissionsProvider>();
            permissions.Setup(
                p =>
                p.HasPermissions(It.Is<IUserIdentity>(x => x != null && x.UserName.Equals("alice")), SystemPermissions.ListStores))
                       .Returns(true);
            var userValidator = new Mock<IUserValidator>();
            userValidator.Setup(v => v.Validate("alice", "password"))
                         .Returns(new MockUserIdentity("alice", new string[0]));
            var mockBrightstar = new Mock<IBrightstarService>();
            mockBrightstar.Setup(s => s.ListStores()).Returns(new string[0]);
            var bootstrapper = new FakeNancyBootstrapper(mockBrightstar.Object, new BasicAuthAuthenticationProvider(new BasicAuthenticationConfiguration(userValidator.Object, "test")),
                                                new FallbackStorePermissionsProvider(StorePermissions.All),
                                                permissions.Object);
            var app = new Browser(bootstrapper);

            var response = app.Get("/", c =>
            {
                c.BasicAuth("alice", "password");
                c.Accept(MediaRange.FromString("application/json"));
            });
            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));

            permissions.VerifyAll();
            userValidator.VerifyAll();
            mockBrightstar.VerifyAll();
        }
        public void GetRecommendations_PerformsCorrectRequest()
        {
            //Setup
            UserReqStub request = new UserReqStub("ExternalID", "DevKey", "api.careerbuilder.com", "", "");

            //Mock crap
            RestResponse<List<RecommendJobResult>> response = new RestResponse<List<RecommendJobResult>>();
            response.Data = new List<RecommendJobResult>();
            
            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("ExternalID", "ExternalID"));
            restReq.SetupSet(x => x.RootElement = "RecommendJobResults");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/recommendations/foruser");
            restClient.Setup(x => x.Execute<List<RecommendJobResult>>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;

            //Assert//
            List<RecommendJobResult> resp = request.GetRecommendations();
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
        public void Build_Parameters_ContenstOfFilesAreCorrect()
        {
            var filePersisterMockFactory = new Mock<IFilePersister>();
            //Project file
            filePersisterMockFactory.Setup(fp => fp.Save(It.IsAny<string>()
                , It.Is<string>(content =>
                    content.Contains("<testProject")
                    && content.Contains("applicationBaseDirectory=\"..\\..\\..\\\"")
                    && content.Contains(@"<file>..\..\..\ts.NBi.NUnit.Runtime.dll</file>")
                    && content.Contains(@"<hintDirectory>..\..\..\Framework\Version\</hintDirectory>")
                    )
                ));
            //
            filePersisterMockFactory.Setup(fp => fp.Save(It.IsAny<string>()
                , It.Is<string>(content =>
                    content.Contains("<nbi testSuite=\"TestSuites\\Serie\\Alpha\\ts.nbits\"/>")
                    )
                ));

            var filePersister = filePersisterMockFactory.Object;

            var builder = new GallioRunnerConfigBuilder(filePersister);
            builder.Build(
                    @"C:\QA\",
                    @"..\..\..\",
                    @"Framework\Version\",
                    @"TestSuites\Serie\Alpha\",
                    "ts");

            filePersisterMockFactory.VerifyAll();
        }
        public void ShouldCallSetBackgroundColorOnlyOnceWithNestedCallsToOnAndOff()
        {
            // GIVEN
            var domContainer = new Mock<DomContainer>().Object;
            var nativeElementMock = new Mock<INativeElement>();
            var element = new Element(domContainer, nativeElementMock.Object);

            Settings.HighLightColor = "myTestColor";
            var highLight = new HighlightAction(element);

            nativeElementMock.Expect(nativeElement => nativeElement.IsElementReferenceStillValid()).Returns(true);
            nativeElementMock.Expect(nativeElement => nativeElement.GetStyleAttributeValue("backgroundColor")).Returns("initialColor").AtMostOnce();
            nativeElementMock.Expect(nativeElement => nativeElement.SetStyleAttributeValue("backgroundColor", "myTestColor")).AtMostOnce();
            nativeElementMock.Expect(nativeElement => nativeElement.SetStyleAttributeValue("backgroundColor", "initialColor")).AtMostOnce();

            // WHEN
            highLight.On();
            highLight.On();
            highLight.On();
            highLight.Off();
            highLight.Off();
            highLight.Off();

            // THEN
            nativeElementMock.VerifyAll();
        }
        public void TestGivenNavigateToPageStepWithArguments()
        {
            var testPage = new Mock<IPage>();

            var pipelineService = new Mock<IActionPipelineService>(MockBehavior.Strict);
            pipelineService.Setup(p => p.PerformAction<PageNavigationAction>(
                null,
                It.Is<PageNavigationAction.PageNavigationActionContext>(c => c.PropertyName == "mypage" && 
                    c.PageAction == PageNavigationAction.PageAction.NavigateToPage && 
                    c.PageArguments != null && c.PageArguments.Count == 2)))
                .Returns(ActionResult.Successful(testPage.Object));

            var scenarioContext = new Mock<IScenarioContextHelper>(MockBehavior.Strict);
            scenarioContext.Setup(s => s.SetValue(It.IsAny<IPage>(), PageStepBase.CurrentPageKey));

            var tokenManager = new Mock<ITokenManager>(MockBehavior.Strict);
            tokenManager.Setup(t => t.GetToken(It.IsAny<string>())).Returns<string>(s => s);

            var steps = new PageNavigationSteps(scenarioContext.Object, pipelineService.Object, tokenManager.Object);

            var table = new Table("Id", "Part");
            table.AddRow("1", "A");

            steps.GivenNavigateToPageWithArgumentsStep("mypage", table);

            scenarioContext.VerifyAll();
            pipelineService.VerifyAll();
        }
Example #22
0
        public void TestExecuteClearsDataIfElementIsFound()
        {
            var propData = new Mock<IPropertyData>(MockBehavior.Strict);
            propData.Setup(p => p.ClearData());

            // ReSharper disable once RedundantAssignment
            IPropertyData element = null;

            var locator = new Mock<IElementLocator>(MockBehavior.Strict);
            locator.Setup(p => p.TryGetElement("myitem", out element)).Returns(false);
            locator.Setup(p => p.GetProperty("myitem")).Returns(propData.Object);

            var getItemAction = new ClearDataAction
            {
                ElementLocator = locator.Object
            };

            var context = new ClearDataAction.ClearDataContext("myitem");
            var result = getItemAction.Execute(context);

            Assert.AreEqual(true, result.Success);

            locator.VerifyAll();
            propData.VerifyAll();
        }
        public void Fetch()
        {
            var person = EntityCreator.Create<E.Person>();
            var people = new InMemoryDbSet<E.Person> { person };
            var context = new Mock<IEntityContext>(MockBehavior.Strict);
            context.Setup(_ => _.People).Returns(people);
            context.Setup(_ => _.Dispose());

            var personViewFactory = new Mock<IObjectFactory<IPersonView>>(MockBehavior.Strict);
            personViewFactory
                .Setup(_ => _.FetchChild(It.Is<int>(__ => __ == person.Id)))
                .Returns(Mock.Of<IPersonView>());

            var container = new ContainerBuilder();
            container.Register<IEntityContext>(_ => context.Object);
            container.Register<IObjectFactory<IPersonView>>(_ => personViewFactory.Object);

            using (container.Build().Bind(() => IoC.Container))
            {
                var actual = DataPortal.Fetch<PersonCollectionView>();
                Assert.IsNotNull(actual);
                Assert.AreEqual(1, actual.Count, "Count");
            }

            context.VerifyAll();
            personViewFactory.VerifyAll();
        }
Example #24
0
        public void LogActivity_Complete_writes_current_method_name()
        {
            var methodName = MethodBase.GetCurrentMethod().Name;
            var observer = new Mock<IObserver<LogEntry>>();
            observer
                .Setup(
                    o => o.OnNext(
                        It.Is<LogEntry>(
                            e => e.CallingMethod == methodName &&
                                 e.EventType == TraceEventType.Stop)));

            var helper = new AsyncTestHelper();

            using (var activity = Log.Enter(() => { }))
            using (TestHelper.LogToConsole())
            using (observer.Object.SubscribeToLogEvents())
            {
                var result = helper.BeginSomething(
                    _ => activity.Complete(() => { }),
                    activity);
                helper.EndSomething(result);
            }

            observer.VerifyAll();
        }
        public void shouldGetCalorieHistory()
        {
            var expectedUserIngredients = GetExpectedUserIngredients(todaysDate);
            var repositoryMock = new Mock<IUserIngredientRepository>();
            var nutrientRepositoryMock = new Mock<INutrientRepository>();
            var nutrientMock = new Mock<Nutrient>();
            var expectedNutrientId = 3;
            nutrientMock.Setup(x => x.Id).Returns(expectedNutrientId);

            var firstDate = todaysDate.AddDays(-100).Date;
            var lastDate = todaysDate;
            nutrientRepositoryMock.Setup(x => x.GetByName(NutrientEntity.EnergyInKcal.ToString())).Returns(nutrientMock.Object);
            repositoryMock.Setup(x => x.GetUserIngredientsByUser(It.IsAny<int>(), firstDate, lastDate.AddDays(1))).Returns(expectedUserIngredients);
            var returnedValues = new UserIngredientBusinessLogic(repositoryMock.Object, null, nutrientRepositoryMock.Object).GetNutrientHistory(NutrientEntity.EnergyInKcal, new User());

            repositoryMock.VerifyAll();
            nutrientRepositoryMock.VerifyAll();

            var todaysUserIngredients = (from ui in expectedUserIngredients where ui.Date == todaysDate select ui);
            var oldUserIngredients = (from ui in expectedUserIngredients where ui.Date == todaysDate.AddDays(-100) select ui);

            Assert.That(returnedValues.Id, Is.EqualTo(expectedNutrientId));

            Assert.That(returnedValues.GetValue(firstDate).Value, Is.EqualTo(oldUserIngredients.Sum(x => x.GetActualCalorieCount(y => y.GetNutrient(NutrientEntity.EnergyInKcal).Value))));
            Assert.That(returnedValues.GetValue(lastDate).Value, Is.EqualTo(todaysUserIngredients.Sum(x => x.GetActualCalorieCount(y => y.GetNutrient(NutrientEntity.EnergyInKcal).Value))));
        }
        public void op_Verify_IRepository()
        {
            var key = AlphaDecimal.Random();

            var obj = new RepositoryModifiedSinceKey<RandomObject>
                          {
                              Record1 =
                                  {
                                      Key = key
                                  }
                          };

            var repository = new Mock<IRepository<RandomObject>>();
            repository
                .Setup(x => x.Insert(obj.Record1))
                .Returns(obj.Record1)
                .Verifiable();
            repository
                .Setup(x => x.ModifiedSince(key, DateTime.MaxValue))
                .Returns(false)
                .Verifiable();
            repository
                .Setup(x => x.ModifiedSince(key, DateTime.MinValue))
                .Returns(true)
                .Verifiable();

            obj.Verify(repository.Object);

            repository.VerifyAll();
        }
        public void ShouldCallExceptionHandlerOnUncaughtException()
        {
            var ex = new Exception();
            var exceptionHandlerMock = new Mock<IExceptionHandler<object>>();
            _batchEventProcessor.SetExceptionHandler(exceptionHandlerMock.Object);

            _batchHandlerMock.Setup(bh => bh.OnEvent(_ringBuffer[0], 0, true))
                             .Throws(ex); // OnNext raises an expcetion

            exceptionHandlerMock.Setup(bh => bh.HandleEventException(ex, 0, _ringBuffer[0]))
                             .Callback(() => _countDownEvent.Signal()); // Exception should be handled here and signal the CDE

            var thread = new Thread(_batchEventProcessor.Run);
            thread.Start();

            _ringBuffer.Publish(_ringBuffer.Next());

            _countDownEvent.Wait(50);

            _batchEventProcessor.Halt();
            thread.Join();

            _batchHandlerMock.VerifyAll();
            exceptionHandlerMock.VerifyAll();
        }
        public void WhenMeetingsAreReturned_ThenViewModelIsPopulated()
        {
            var asyncResultMock = new Mock<IAsyncResult>();

            var calendarServiceMock = new Mock<ICalendarService>(MockBehavior.Strict);
            AsyncCallback callback = null;
            calendarServiceMock
                .Setup(svc => svc.BeginGetMeetings(It.IsAny<AsyncCallback>(), null))
                .Callback<AsyncCallback, object>((ac, o) => callback = ac)
                .Returns(asyncResultMock.Object);
            var meeting = new Meeting { };
            calendarServiceMock
                .Setup(svc => svc.EndGetMeetings(asyncResultMock.Object))
                .Returns(new[] { meeting });


            var viewModel = new CalendarViewModel(calendarServiceMock.Object, new Mock<IRegionManager>().Object);

            this.EnqueueConditional(() => callback != null);

            this.EnqueueCallback(
                () =>
                {
                    callback(asyncResultMock.Object);
                });

            this.EnqueueCallback(
                () =>
                {
                    CollectionAssert.AreEqual(viewModel.Meetings, new[] { meeting });
                    calendarServiceMock.VerifyAll();
                });

            this.EnqueueTestComplete();
        }
Example #29
0
        public void Dicovery_Source_Empty()
        {
            // Setup

            var request = new Mock<HttpRequestBase>(MockBehavior.Strict);
            string request_content = String.Format("<?xml version=\"1.0\"?><methodCall><methodName>pingback.ping</methodName><params><param><value><string>{0}</string></value></param><param><value><string>{1}</string></value></param></params></methodCall>",
                "http://source/1", "http://target/1");
            request.SetupGet(x => x.InputStream).Returns(new MemoryStream(new UTF8Encoding().GetBytes(request_content)));

            var webRequest = new Mock<IHttpWebRequestImplementation>(MockBehavior.Strict);
            var webResponse = new Mock<IHttpWebResponseImplementation>(MockBehavior.Strict);

            webRequest.Setup(x => x.Create(new Uri("http://source/1", UriKind.Absolute))).Returns(webRequest.Object);
            webRequest.Setup(x => x.GetResponse()).Returns(webResponse.Object);

            webResponse.Setup(x => x.Close());
            webResponse.SetupGet(x => x.IsHttpStatusCode2XX).Returns(true);
            webResponse.Setup(x => x.GetResponseStream()).Returns(new MemoryStream(new UTF8Encoding().GetBytes("")));

            // Test

            var pingback = new Pingback(webRequest.Object);

            var result = pingback.Receive(request.Object, null);

            // Verify

            request.VerifyAll();
            webRequest.VerifyAll();
            webResponse.VerifyAll();

            Assert.False(result.Valid);
            Assert.Equal("http://source/1", result.SourceUri.ToString().ToLowerInvariant());
            Assert.Equal("http://target/1", result.TargetUri.ToString().ToLowerInvariant());
        }
        public void Search_PerformsCorrectRequest()
        {
            //Setup
            JobSearchStub request = new JobSearchStub("DevKey", "api.careerbuilder.com","","");
            
            //Mock crap
            RestResponse<ResponseJobSearch> response = new RestResponse<ResponseJobSearch>();
            response.Data = new ResponseJobSearch();
                        
            var restReq = new Mock<IRestRequest>();
            restReq.Setup(x => x.AddParameter("DeveloperKey", "DevKey"));
            restReq.Setup(x => x.AddParameter("CountryCode", "NL"));
            restReq.SetupSet(x => x.RootElement = "ResponseJobSearch");

            var restClient = new Mock<IRestClient>();
            restClient.SetupSet(x => x.BaseUrl = "https://api.careerbuilder.com/v1/jobsearch");
            restClient.Setup(x => x.Execute<ResponseJobSearch>(It.IsAny<IRestRequest>())).Returns(response);

            request.Request = restReq.Object;
            request.Client = restClient.Object;
            
            //Assert
            ResponseJobSearch resp = request.WhereCountryCode(CountryCode.NL).Search();
            restReq.Verify();
            restClient.VerifyAll();
        }