Beispiel #1
1
        private static void SetupNinJect(MoqMockingKernel kernel)
        {
            if (DEBUGING)
            {
                var MockEmailManager = kernel.GetMock<IEmailManager>();
                MockEmailManager.Setup(x => x.sendEmail()).Returns("Return from unit test mock");
            } else
            {
                kernel.Bind<IEmailManager>()
                    .To<EmailManager>()
                    .WithPropertyValue("message", "setup from NinJect");
            }

            kernel.Bind<IAddress>()
                .To<Address>()
                .WithPropertyValue("Postcode", "PR1 1UT");

            kernel.Bind<IApplicant>()
                .To<Applicant>()
                .WithPropertyValue("EmailAddress", "*****@*****.**")
                .WithConstructorArgument("address", kernel.Get<IAddress>());

            kernel.Bind<IApplication>()
                .To<Application>()
                .WithPropertyValue("emailManager", kernel.Get<IEmailManager>())
                .WithConstructorArgument("applicant", kernel.Get<IApplicant>());
        }
Beispiel #2
0
        public void ReturnGetQueryTest()
        {
            var uow   = _kernel.Get <NeutrinoUnitOfWork>();
            var count = uow.AppSettingDataService.GetQuery().Count();

            Assert.AreEqual(count, uow.AppSettingDataService.GetCount());
        }
Beispiel #3
0
        IPlayViewModel setupStandardMock(MoqMockingKernel kernel, IRoutingState router, Action extraSetup = null)
        {
            kernel.Bind <IPlayViewModel>().To <PlayViewModel>();

            var playApi = kernel.GetMock <IPlayApi>();

            playApi.Setup(x => x.ListenUrl()).Returns(Observable.Never <string>());
            playApi.Setup(x => x.ConnectToSongChangeNotifications()).Returns(Observable.Never <Unit>());
            playApi.Setup(x => x.NowPlaying()).Returns(Observable.Return(Fakes.GetSong()));
            playApi.Setup(x => x.Queue()).Returns(Observable.Return(Fakes.GetAlbum()));
            playApi.Setup(x => x.FetchImageForAlbum(It.IsAny <Song>())).Returns(Observable.Return <BitmapImage>(null));

            kernel.GetMock <IScreen>().Setup(x => x.Router).Returns(router);

            kernel.GetMock <ILoginMethods>()
            .Setup(x => x.EraseCredentialsAndNavigateToLogin())
            .Callback(() => router.Navigate.Execute(kernel.Get <IWelcomeViewModel>()));

            kernel.GetMock <ILoginMethods>()
            .Setup(x => x.CurrentAuthenticatedClient)
            .Returns(kernel.Get <IPlayApi>());

            if (extraSetup != null)
            {
                extraSetup();
            }

            RxApp.ConfigureServiceLocator((t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));
            return(kernel.Get <IPlayViewModel>());
        }
Beispiel #4
0
        static ISearchViewModel setupStandardFixture(MoqMockingKernel kernel, IRoutingState router = null)
        {
            router = router ?? new RoutingState();
            kernel.Bind <ISearchViewModel>().To <SearchViewModel>();
            kernel.Bind <IBlobCache>().To <TestBlobCache>().Named("UserAccount");
            kernel.Bind <IBlobCache>().To <TestBlobCache>().Named("LocalMachine");

            kernel.GetMock <IPlayApi>().Setup(x => x.Search("Foo"))
            .Returns(Observable.Return(new List <Song>()
            {
                Fakes.GetSong()
            }))
            .Verifiable();

            kernel.GetMock <ILoginMethods>().Setup(x => x.CurrentAuthenticatedClient).Returns(kernel.Get <IPlayApi>());
            kernel.GetMock <IScreen>().Setup(x => x.Router).Returns(router);

            var img = new BitmapImage();

            kernel.GetMock <IPlayApi>().Setup(x => x.FetchImageForAlbum(It.IsAny <Song>()))
            .Returns(Observable.Return(img))
            .Verifiable();

            RxApp.ConfigureServiceLocator((t, s) => kernel.Get(t, s), (t, s) => kernel.GetAll(t, s));

            var fixture = kernel.Get <ISearchViewModel>();

            return(fixture);
        }
Beispiel #5
0
        public void ServiceEntryPointUsesNamespaceAsServiceNameByDefault()
        {
            var service = _kernel.Get <TestPollingService>();

            _kernel.Bind <IStandardService>().ToConstant(service);
            var ep = _kernel.Get <ServiceEntryPoint>();

            Assert.AreEqual("Handsome.Pete.ServiceTemplateTests", ep.AppSettings.InstallServiceName);
        }
Beispiel #6
0
        public void ExecutingCreateCustomerCommandShowsCustomerView()
        {
            var customerViewMock = _kernel.GetMock <ICustomerView>();

            customerViewMock.Setup(v => v.ShowDialog());
            var sut = _kernel.Get <MainViewModel>();

            sut.CreateCustomerCommand.Execute(null);
            customerViewMock.VerifyAll();
        }
Beispiel #7
0
        public void RoomService_GetAll()
        {
            // Arrange
            IRoomService roomService = _kernel.Get <IRoomService>();

            // Act
            ICollection <Room> rooms = roomService.GetAll();

            // Assert
            Assert.IsTrue(rooms.Any(), "Please run Seed() method from Foundation project.");
        }
Beispiel #8
0
        public void GettingCustomersCallsRepositoryGetAll()
        {
            var repositoryMock = kernel.GetMock <ICustomerRepository>();

            repositoryMock.Setup(r => r.GetAll());

            var sut = kernel.Get <MainViewModel>();

            var customers = sut.Customers;

            repositoryMock.VerifyAll();
        }
Beispiel #9
0
        public void ConcatTest()
        {
            _kernel.GetMock <IThingA>()
            .Setup(thing => thing.GetSomeString())
            .Returns("Goodbye");

            var classUnderTest = _kernel.Get <SomeClass>();
            var expectedResult = "Hello" + "Goodbye";
            var actualResult   = classUnderTest.ConcatTopThing("Hello");

            output.WriteLine($"ActualResult: {actualResult}");
            Assert.Equal(expectedResult, actualResult);
        }
Beispiel #10
0
        public void SetUpBase()
        {
            MockingKernel = new MoqMockingKernel();

            MockingKernel.Load <Modules.Mapping>();

            MockingKernel.Load <TestModules.Logging>();
            MockingKernel.Load <TestModules.Mediatr>();
            MockingKernel.Load <TestModules.EntityFramework>();

            Mediator = MockingKernel.Get <IMediator>();

            DbContext = MockingKernel.Get <ApplicationDbContext>();
        }
Beispiel #11
0
        public void FeedWithEntryIsPassedThroughFromPhabricator()
        {
            var entry = new AtomEntry(
                new AtomId(),
                new AtomTextConstruct("test entry"),
                DateTime.Now);
            var expectedFeed = new AtomFeed();

            expectedFeed.AddEntry(entry);

            var kernel = new MoqMockingKernel();

            IoC.ReplaceKernel(kernel);
            kernel.Unbind <IPhabricator>();
            var mock = kernel.GetMock <IPhabricator>();

            mock.Setup(m => m.GetFeed("1")).Returns(expectedFeed);
            var controller = kernel.Get <HomeController>();
            var result     = controller.Index();

            Assert.IsType <ViewResult>(result);
            var viewResult = result as ViewResult;

            Assert.IsType <FeedViewModel>(viewResult.Model);
            Assert.NotNull(((FeedViewModel)viewResult.Model).Feed);
            var feedObj = ((FeedViewModel)viewResult.Model).Feed;

            Assert.IsType <AtomFeed>(feedObj);
            var actualFeed = feedObj as AtomFeed;

            Assert.True(actualFeed.Entries.Count() == 1);
            Assert.True(actualFeed.Entries.First().Title.Content == "test entry");
            Assert.Equal(actualFeed, expectedFeed);
        }
        public void BadPasswordMeansErrorMessage()
        {
            var mock = new MoqMockingKernel();

            mock.Bind<ILoginViewModel>().To(typeof(LoginViewModel));

            mock.Bind<Func<IObservable<Unit>>>()
                .ToConstant<Func<IObservable<Unit>>>(() => Observable.Throw<Unit>(new Exception("Bad Stuff")))
                .Named("confirmUserPass");

            var fixture = mock.Get<ILoginViewModel>();

            fixture.User = "******";
            fixture.Password = "******";

            fixture.Confirm.CanExecute(null).Should().BeTrue();

            UserError error = null;
            using(UserError.OverrideHandlersForTesting(x => { error = x; return Observable.Return(RecoveryOptionResult.CancelOperation); })) {
                fixture.Confirm.Execute(null);
            }

            error.Should().NotBeNull();
            this.Log().Info("Error Message: {0}", error.ErrorMessage);
            error.ErrorMessage.Should().NotBeNullOrEmpty();
        }
        public void GetAll_Should_GetAll_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _orderFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Order> >()
                .SetupData(input);

                var service = kernel.Get <OrderService>();
                var result  = service.GetAll();

                result.Count.ShouldBe(input.Count);
                for (var i = 0; i < result.Count; i++)
                {
                    result[i].ID.ShouldBe(input[i].ID);
                    result[i].Customer.IdentyficationNumber.ShouldBe(input[i].Customer.IdentyficationNumber);
                    result[i].CustomerID.ShouldBe(input[i].CustomerID);
                    result[i].Comment.ShouldBe(input[i].Comment);
                    result[i].Date_Rented.ShouldBe(input[i].Date_Rented);
                    result[i].Date_Return.ShouldBe(input[i].Date_Return);
                    result[i].Employee.Login.ShouldBe(input[i].Employee.Login);
                    result[i].EmployeeID.ShouldBe(input[i].EmployeeID);
                }
            }
        }
        public void Update_Should_Update_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var data = _orderFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Order> >()
                .SetupData(data);

                var service = kernel.Get <OrderService>();
                var inputID = service.Get(1).ID;
                var input   = _orderFaker.Generate(1).LastOrDefault();
                input.ID = inputID;

                Action act = () => { service.Update(_mapper.Map <OrderDetailViewModel>(input)); };
                Assert.ThrowsException <FileLoadException>(act);
                var result = data[1];

                result.ID.ShouldBe(input.ID);
                result.Customer.IdentyficationNumber.ShouldBe(input.Customer.IdentyficationNumber);
                result.CustomerID.ShouldBe(input.ID);
                result.Comment.ShouldBe(input.Comment);
                result.Date_Rented.ShouldBe(input.Date_Rented);
                result.Date_Return.ShouldBe(input.Date_Return);
                result.Employee.Login.ShouldBe(input.Employee.Login);
                result.EmployeeID.ShouldBe(input.EmployeeID);
            }
        }
        public void Add_Should_Add_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _categoryFaker.Generate(1).FirstOrDefault();
                var data  = _categoryFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Category> >()
                .SetupData(data);

                var service = kernel.Get <CategoryService>();

                Action act = () => { service.Add(_mapper.Map <CategoryDetailViewModel>(input)); };
                Assert.ThrowsException <FileLoadException>(act);

                data.Count.ShouldBe(6);
                var result = data.LastOrDefault();

                result.ID.ShouldBe(input.ID);
                result.ParentCategory.ShouldBe(input.ParentCategory);
                result.Name.ShouldBe(input.Name);
                result.PricePerDay.ShouldBe(input.PricePerDay);
                result.Items.Count.ShouldBe(input.Items.Count);
                result.SubCategories.Count.ShouldBe(input.SubCategories.Count);
            }
        }
Beispiel #16
0
        public void GetUserByUserNameAndPassword_Should_Get_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _employeeFaker.Generate(5).ToList();
                input[2].Login    = "******";
                input[2].Password = "******";     //Password should be updated with change of Hashing algorithm

                kernel.GetMock <DbSet <Employee> >()
                .SetupData(input);

                var service = kernel.Get <EmployeeService>();
                var result  = service.GetUserByUserNameAndPassword("Login", "P4SSw0rd");

                result.ID.ShouldBe(input[2].ID);
                result.Address.ShouldBe(input[2].Address);
                result.EmploymentDate.ShouldBe(input[2].EmploymentDate);
                result.FirstName.ShouldBe(input[2].FirstName);
                result.LastName.ShouldBe(input[2].LastName);
                result.Login.ShouldBe(input[2].Login);
                result.PermissionLevel.ShouldBe(input[2].PermissionLevel);
                result.PhoneNumber.ShouldBe(input[2].PhoneNumber);
                result.Salary.ShouldBe(input[2].Salary);
            }
        }
        public void BadPasswordMeansErrorMessage()
        {
            var mock = new MoqMockingKernel();

            mock.Bind <ILoginViewModel>().To(typeof(LoginViewModel));

            mock.Bind <Func <IObservable <Unit> > >()
            .ToConstant <Func <IObservable <Unit> > >(() => Observable.Throw <Unit>(new Exception("Bad Stuff")))
            .Named("confirmUserPass");

            var fixture = mock.Get <ILoginViewModel>();

            fixture.User     = "******";
            fixture.Password = "******";

            fixture.Confirm.CanExecute(null).Should().BeTrue();

            UserError error = null;

            using (UserError.OverrideHandlersForTesting(x => { error = x; return(Observable.Return(RecoveryOptionResult.CancelOperation)); })) {
                fixture.Confirm.Execute(null);
            }

            error.Should().NotBeNull();
            this.Log().Info("Error Message: {0}", error.ErrorMessage);
            error.ErrorMessage.Should().NotBeNullOrEmpty();
        }
Beispiel #18
0
        public void Setup()
        {
            kernel = new MoqMockingKernel();
            kernel.Load(new ZappModule());

            factory = kernel.Get <IPackageFactory>();
        }
Beispiel #19
0
        public void Get_Should_Get_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var data = _itemFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Item> >()
                .SetupData(data);

                var input = data.SingleOrDefault(x => x.ID == 1);

                var service = kernel.Get <ItemService>();
                var result  = service.Get(1);

                result.ID.ShouldBe(input.ID);
                result.Avaiable.ShouldBe(input.Avaiable);
                result.CategoryID.ShouldBe(input.CategoryID.ToString());
                result.Category.Name.ShouldBe(input.Category.Name);
                result.Manufacturer.ShouldBe(input.Manufacturer);
                result.ModelName.ShouldBe(input.ModelName);
                result.Size.ShouldBe(input.Size);
                result.Purchase_date.ShouldBe(input.Purchase_date);
                result.Rented_Items.Count.ShouldBe(input.Rented_Items.Count);
                result.Barcode.ShouldBe(input.Barcode);
            }
        }
Beispiel #20
0
        public void Add_Should_Add_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _paymentFaker.Generate(1).FirstOrDefault();
                var data  = _paymentFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Payment> >()
                .SetupData(data);

                var service = kernel.Get <SkiRent.Services.PaymentService>();

                Action act = () => { service.Add(_mapper.Map <PaymentBasicViewModel>(input)); };
                Assert.ThrowsException <FileLoadException>(act);


                data.Count.ShouldBe(6);
                var result = data.LastOrDefault();

                result.ID.ShouldBe(input.ID);
                result.Amount.ShouldBe(input.Amount);
                result.ExchangeRate.ShouldBe(input.ExchangeRate);
                result.OrderID.ShouldBe(input.OrderID);
                result.PaymentDate.ShouldBe(input.PaymentDate);
                result.Currency.ShouldBe(input.Currency);
            }
        }
Beispiel #21
0
        public void GetAll_Should_Get_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _itemFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Item> >()
                .SetupData(input);

                var service = kernel.Get <ItemService>();
                var result  = service.GetAll();

                result.Count.ShouldBe(input.Count);
                for (int i = 0; i < result.Count; i++)
                {
                    result[i].ID.ShouldBe(input[i].ID);
                    result[i].Avaiable.ShouldBe(input[i].Avaiable);
                    result[i].CategoryID.ShouldBe(input[i].CategoryID.ToString());
                    result[i].Category.Name.ShouldBe(input[i].Category.Name);
                    result[i].Manufacturer.ShouldBe(input[i].Manufacturer);
                    result[i].ModelName.ShouldBe(input[i].ModelName);
                    result[i].Size.ShouldBe(input[i].Size);
                    result[i].Purchase_date.ShouldBe(input[i].Purchase_date);
                    result[i].Barcode.ShouldBe(input[i].Barcode);
                }
            }
        }
        public void ProperCreditCardShouldReturnSuccessResult()
        {
            // arrange
            var creditCard = new CreditCard
            {
                CardNumber         = "4111222233334444",
                CardHolderFullName = "Test Tester",
                Amount             = 100,
                Cvv            = 123,
                ExpirationDate = new DateTime(2020, 12, 4)
            };

            var creditCardResult = new CreditCardClientResult
            {
                AuthorizationCode = 1234,
                TransactionId     = "This is my result",
                CreditCard        = creditCard
            };

            var creditCardClientMock = _kernel.GetMock <ICreditCardClient>();

            creditCardClientMock.Setup(mock => mock.SendRequest(It.IsAny <CreditCard>())).Returns(creditCardResult);

            var client = _kernel.Get <ICreditCardClient>();

            CreditCardClientResult clientResult = client.SendRequest(creditCard);

            clientResult.AuthorizationCode.Should().Be(1234);
            clientResult.TransactionId.Should().NotBeNullOrEmpty();
            clientResult.CreditCard.Should().NotBeNull();
            clientResult.CreditCard.CardNumber.Should().Be("4111222233334444");
        }
Beispiel #23
0
        public void BuildStatusIsPassedThroughFromBuildServerClass()
        {
            var kernel = new MoqMockingKernel();

            IoC.ReplaceKernel(kernel);
            kernel.Unbind <IBuildServer>();
            var mock = kernel.GetMock <IBuildServer>();

            mock.Setup(m => m.IsBuildServerOnline()).Returns(false);
            var controller = kernel.Get <DownloadController>();
            var result     = controller.Index();

            Assert.IsType <ViewResult>(result);
            var viewResult = result as ViewResult;

            Assert.IsType <DownloadViewModel>(viewResult.Model);
            Assert.Equal(false, ((DownloadViewModel)viewResult.Model).BuildServerOnline);

            mock.Setup(m => m.IsBuildServerOnline()).Returns(true);
            result = controller.Index();
            Assert.IsType <ViewResult>(result);
            viewResult = result as ViewResult;
            Assert.IsType <DownloadViewModel>(viewResult.Model);
            Assert.Equal(true, ((DownloadViewModel)viewResult.Model).BuildServerOnline);
        }
Beispiel #24
0
        public void Update_Should_Update_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var data = _itemFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Item> >()
                .SetupData(data);

                var service = kernel.Get <ItemService>();
                var inputID = service.Get(1).ID;
                var input   = _itemFaker.Generate(1).FirstOrDefault();
                input.ID = inputID;
//
//                Action act = () => { service.Update(_mapper.Map<ItemDetailViewModel>(input)); };
//                Assert.ThrowsException<FileLoadException>(act);
//                var result = data[1];
//
//                data.Count.ShouldBe(5);
//                result.ID.ShouldBe(input.ID);
//                result.Avaiable.ShouldBe(input.Avaiable);
//                result.CategoryID.ShouldBe(input.CategoryID);
//                result.Category.Name.ShouldBe(input.Category.Name);
//                result.Manufacturer.ShouldBe(input.Manufacturer);
//                result.ModelName.ShouldBe(input.ModelName);
//                result.Size.ShouldBe(input.Size);
//                result.Purchase_date.ShouldBe(input.Purchase_date);
//                result.Rented_Items.Count.ShouldBe(input.Rented_Items.Count);
//                result.Barcode.ShouldBe(input.Barcode);
            }
        }
        public void RepoSelectionIntegrationSmokeTest()
        {
            var mock = new MoqMockingKernel();

            var client = new RestClient("https://api.github.com")
            {
                Authenticator = new HttpBasicAuthenticator("fakepaulbetts", "omg this password is sekrit"),
            };

            mock.Bind <IRestClient>().ToConstant(client);
            mock.Bind <IGitHubApi>().To <GitHubApi>();
            mock.Bind <IRepoSelectionViewModel>().To <RepoSelectionViewModel>();

            (new TestScheduler()).With(sched => {
                var fixture = mock.Get <IRepoSelectionViewModel>();

                sched.Start();

                foreach (var v in fixture.Organizations)
                {
                    v.Model.Should().NotBeNull();
                    this.Log().Info(v.Model.login);

                    v.Repositories.Count.Should().BeGreaterThan(0);
                }

                fixture.Organizations.Count.Should().BeGreaterThan(0);
            });
        }
Beispiel #26
0
        public void GetAll_Should_GetAll_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _customerFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Customer> >()
                .SetupData(input);

                var service = kernel.Get <CustomerService>();
                var result  = service.GetAll();

                result.Count.ShouldBe(input.Count);
                for (var i = 0; i < result.Count; i++)
                {
                    result[i].ID.ShouldBe(input[i].ID);
                    result[i].FirstName.ShouldBe(input[i].FirstName);
                    result[i].LastName.ShouldBe(input[i].LastName);
                    result[i].Address.ShouldBe(input[i].Address);
                    result[i].PhoneNumber.ShouldBe(input[i].PhoneNumber);
                    result[i].IdentyficationNumber.ShouldBe(input[i].IdentyficationNumber);
                }
            }
        }
Beispiel #27
0
        public void Add_Should_Add_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _customerFaker.Generate(1).FirstOrDefault();
                var data  = _customerFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Customer> >()
                .SetupData(data);

                var service = kernel.Get <CustomerService>();

                Action act = () => { service.Add(_mapper.Map <CustomerDetailViewModel>(input)); };
                Assert.ThrowsException <FileLoadException>(act);

                data.Count.ShouldBe(6);
                var result = data.LastOrDefault();

                result.ID.ShouldBe(input.ID);
                result.FirstName.ShouldBe(input.FirstName);
                result.LastName.ShouldBe(input.LastName);
                result.Address.ShouldBe(input.Address);
                result.PhoneNumber.ShouldBe(input.PhoneNumber);
                result.IdentyficationNumber.ShouldBe(input.IdentyficationNumber);
                result.Orders.Count.ShouldBe(input.Orders.Count);
            }
        }
        public void RepoSelectionIntegrationSmokeTest()
        {
            var mock = new MoqMockingKernel();

            var client = new RestClient("https://api.github.com") {
                Authenticator = new HttpBasicAuthenticator("fakepaulbetts", "omg this password is sekrit"),
            };

            mock.Bind<IRestClient>().ToConstant(client);
            mock.Bind<IGitHubApi>().To<GitHubApi>();
            mock.Bind<IRepoSelectionViewModel>().To<RepoSelectionViewModel>();

            (new TestScheduler()).With(sched => {
                var fixture = mock.Get<IRepoSelectionViewModel>();

                sched.Start();

                foreach(var v in fixture.Organizations) {
                    v.Model.Should().NotBeNull();
                    this.Log().Info(v.Model.login);

                    v.Repositories.Count.Should().BeGreaterThan(0);
                }

                fixture.Organizations.Count.Should().BeGreaterThan(0);
            });
        }
Beispiel #29
0
        public void GetAll_Should_GetAll_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _employeeFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Employee> >()
                .SetupData(input);

                var service = kernel.Get <EmployeeService>();
                var result  = service.GetAll();

                result.Count.ShouldBe(input.Count);
                for (int i = 0; i < result.Count; i++)
                {
                    result[i].ID.ShouldBe(input[i].ID);
                    result[i].Address.ShouldBe(input[i].Address);
                    result[i].EmploymentDate.ShouldBe(input[i].EmploymentDate);
                    result[i].FirstName.ShouldBe(input[i].FirstName);
                    result[i].LastName.ShouldBe(input[i].LastName);
                    result[i].Login.ShouldBe(input[i].Login);
                    result[i].PermissionLevel.ShouldBe(input[i].PermissionLevel);
                    result[i].PhoneNumber.ShouldBe(input[i].PhoneNumber);
                    result[i].Salary.ShouldBe(input[i].Salary);
                }
            }
        }
Beispiel #30
0
        public void Update_Should_Update_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var data = _employeeFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Employee> >()
                .SetupData(data);

                var service = kernel.Get <EmployeeService>();
                var inputID = service.Get(1).ID;
                var input   = _employeeFaker.Generate(1).FirstOrDefault();
                input.ID = inputID;

                Action act = () => { service.Update(_mapper.Map <EmployeeDetailViewModel>(input)); };
                Assert.ThrowsException <FileLoadException>(act);
                var result = data[1];

                data.Count.ShouldBe(5);
                result.ID.ShouldBe(input.ID);
                result.Address.ShouldBe(input.Address);
                result.EmploymentDate.ShouldBe(input.EmploymentDate);
                result.FirstName.ShouldBe(input.FirstName);
                result.LastName.ShouldBe(input.LastName);
                result.Login.ShouldBe(input.Login);
//                result.Password.ShouldBe(AuthorizationHelper.HashPassword(input.Login, input.Password));
                result.PermissionLevel.ShouldBe(input.PermissionLevel);
                result.PhoneNumber.ShouldBe(input.PhoneNumber);
                result.Salary.ShouldBe(input.Salary);
                result.Orders.Count.ShouldBe(input.Orders.Count);
            }
        }
Beispiel #31
0
        public void Get_Should_Get_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var data = _employeeFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Employee> >()
                .SetupData(data);

                var input = data.SingleOrDefault(x => x.ID == 1);

                var service = kernel.Get <EmployeeService>();
                var result  = service.Get(1);

                result.ID.ShouldBe(input.ID);
                result.Address.ShouldBe(input.Address);
                result.EmploymentDate.ShouldBe(input.EmploymentDate);
                result.FirstName.ShouldBe(input.FirstName);
                result.LastName.ShouldBe(input.LastName);
                result.Login.ShouldBe(input.Login);
                result.Password.ShouldBeNull();
                result.PermissionLevel.ShouldBe(input.PermissionLevel);
                result.PhoneNumber.ShouldBe(input.PhoneNumber);
                result.Salary.ShouldBe(input.Salary);
                result.Orders.Count.ShouldBe(input.Orders.Count);
            }
        }
        public void SuccessfulLoginShouldActuallyLogIn()
        {
            var mock = new MoqMockingKernel();

            mock.Bind <ILoginViewModel>().To(typeof(LoginViewModel));

            mock.Bind <Func <IObservable <Unit> > >()
            .ToConstant <Func <IObservable <Unit> > >(() => Observable.Return(Unit.Default))
            .Named("confirmUserPass");

            var fixture = mock.Get <ILoginViewModel>();

            fixture.User     = "******";
            fixture.Password = "******";

            fixture.Confirm.CanExecute(null).Should().BeTrue();

            Tuple <string, string> result = null;

            MessageBus.Current.Listen <Tuple <string, string> >("login").Subscribe(x => result = x);
            fixture.Confirm.Execute(null);

            result.Should().NotBeNull();
            result.Item1.Should().Be(fixture.User);
            result.Item2.Should().Be(fixture.Password);
        }
Beispiel #33
0
        public void GetAll_Should_GetAll_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

                var input = _paymentFaker.Generate(5).ToList();

                kernel.GetMock <DbSet <Payment> >()
                .SetupData(input);

                var service = kernel.Get <SkiRent.Services.PaymentService>();
                var result  = service.GetAll();

                result.Count.ShouldBe(input.Count);
                for (var i = 0; i < result.Count; i++)
                {
                    result[i].ID.ShouldBe(input[i].ID);
                    result[i].Amount.ShouldBe(input[i].Amount);
                    result[i].ExchangeRate.ShouldBe(input[i].ExchangeRate);
                    result[i].OrderID.ShouldBe(input[i].OrderID);
                    result[i].PaymentDate.ShouldBe(input[i].PaymentDate);
                    result[i].Currency.ShouldBe(input[i].Currency);
                }
            }
        }
Beispiel #34
0
        static void Main(string[] args)
        {
            {
                // Without ninJect
                Address add = new Address() { Postcode = "PR2 2UT" };
                Applicant applicant = new Applicant(add);
                applicant.EmailAddress = "*****@*****.**";
                Application app = new Application(applicant);
                app.emailManager = new EmailManager();
                app.emailManager.message = "Setup using basic DI pattern";

                Console.WriteLine(app.sendEmail());
                Console.WriteLine(JsonConvert.SerializeObject(app));

                Console.ReadKey();
            }

            using (var kernel = new MoqMockingKernel())
            {
                SetupNinJect(kernel);

                // With NinJect (includes Mocking as well!
                var app = kernel.Get<IApplication>();

                Console.WriteLine(app.sendEmail());
                Console.WriteLine(JsonConvert.SerializeObject(app.App1));
                Console.ReadKey();
            }
        }
        public void MocksAreStrictIfConfigured()
        {
            var settings = new NinjectSettings();
            settings.SetMockBehavior(MockBehavior.Strict);

            using (var kernel = new MoqMockingKernel(settings))
            {
                var mock = kernel.Get<IDummyService>();

                Assert.Throws<MockException>(() => mock.Do());
            }
        }
        public void SuccessfulLoginIntegrationTest()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IWelcomeViewModel>().To<WelcomeViewModel>();

            var cache = new TestBlobCache(null, (IEnumerable<KeyValuePair<string, byte[]>>)null);
            kernel.Bind<ISecureBlobCache>().ToConstant(cache);

            var mock = kernel.GetMock<IScreen>();
            var routingState = new RoutingState();
            mock.Setup(x => x.Router).Returns(routingState);

            var initialPage = kernel.Get<IRoutableViewModel>();
            kernel.Get<IScreen>().Router.NavigateAndReset.Execute(initialPage);

            var fixture = kernel.Get<IWelcomeViewModel>();
            kernel.Get<IScreen>().Router.Navigate.Execute(fixture);

            fixture.BaseUrl = IntegrationTestUrl.Current;
            fixture.Token = IntegrationTestUrl.Token;
            fixture.OkButton.Execute(null);

            kernel.Get<IScreen>().Router.ViewModelObservable().Skip(1)
                .Timeout(TimeSpan.FromSeconds(10.0), RxApp.TaskpoolScheduler)
                .First();

            fixture.ErrorMessage.Should().BeNull();
            kernel.Get<IScreen>().Router.GetCurrentViewModel().Should().Be(initialPage);
        }
        public void MakeAlbumSearchIntegrationTest()
        {
            var kernel = new MoqMockingKernel();
            var client = new RestClient(IntegrationTestUrl.Current);

            client.AddDefaultHeader("Authorization", IntegrationTestUrl.Token);
            kernel.Bind<IBlobCache>().To<TestBlobCache>();

            var api = new PlayApi(client, kernel.Get<IBlobCache>());

            var result = api.AllSongsOnAlbum("LCD Soundsystem", "Sound Of Silver")
                .Timeout(TimeSpan.FromSeconds(9.0), RxApp.TaskpoolScheduler)
                .First();

            this.Log().Info(String.Join(",", result.Select(x => x.name)));
            result.Count.Should().BeGreaterThan(2);
        }
        public void FetchNowPlayingIntegrationTest()
        {
            var kernel = new MoqMockingKernel();
            var client = new RestClient(IntegrationTestUrl.Current);

            client.AddDefaultHeader("Authorization", IntegrationTestUrl.Token);
            kernel.Bind<IBlobCache>().To<TestBlobCache>();

            var api = new PlayApi(client, kernel.Get<IBlobCache>());

            var result = api.NowPlaying()
                .Timeout(TimeSpan.FromSeconds(9.0), RxApp.TaskpoolScheduler)
                .First();

            this.Log().Info(result.ToString());
            result.id.Should().NotBeNullOrEmpty();
        }
        public void NavigatingToPlayWithoutAPasswordShouldNavigateToLogin()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IPlayViewModel>().To<PlayViewModel>();

            var cache = new TestBlobCache(null, (IEnumerable<KeyValuePair<string, byte[]>>)null);
            kernel.Bind<ISecureBlobCache>().ToConstant(cache);

            kernel.GetMock<ILoginMethods>()
                .Setup(x => x.EraseCredentialsAndNavigateToLogin()).Verifiable();

            var router = new RoutingState();
            kernel.GetMock<IScreen>().Setup(x => x.Router).Returns(router);

            var fixture = kernel.Get<IPlayViewModel>();
            router.Navigate.Execute(fixture);
            kernel.GetMock<ILoginMethods>().Verify(x => x.EraseCredentialsAndNavigateToLogin(), Times.Once());
        }
        static ISongTileViewModel setupStandardFixture(Song song, MoqMockingKernel kernel)
        {
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("UserAccount");
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("LocalMachine");

            kernel.GetMock<IPlayApi>().Setup(x => x.QueueSong(It.IsAny<Song>()))
                .Returns(Observable.Return(Unit.Default))
                .Verifiable();

            kernel.GetMock<IPlayApi>().Setup(x => x.AllSongsOnAlbum(It.IsAny<string>(), It.IsAny<string>()))
                .Returns(Observable.Return(Fakes.GetAlbum()))
                .Verifiable();

            kernel.GetMock<IPlayApi>().Setup(x => x.FetchImageForAlbum(It.IsAny<Song>()))
                .Returns(Observable.Return(new BitmapImage()));

            return new SongTileViewModel(song, kernel.Get<IPlayApi>());
        }
        public void BlankFieldsMeansNoLogin()
        {
            var mock = new MoqMockingKernel();
            mock.Bind<ILoginViewModel>().To(typeof(LoginViewModel));

            var fixture = mock.Get<ILoginViewModel>();

            fixture.Confirm.CanExecute(null).Should().BeFalse();

            fixture.User = "******";
            fixture.Confirm.CanExecute(null).Should().BeFalse();

            fixture.User = "";
            fixture.Password = "******";
            fixture.Confirm.CanExecute(null).Should().BeFalse();

            fixture.User = "******";
            fixture.Confirm.CanExecute(null).Should().BeTrue();
        }
        public void CantHitOkWhenBaseUrlIsntAUrl()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IWelcomeViewModel>().To<WelcomeViewModel>();

            var fixture = kernel.Get<IWelcomeViewModel>();

            fixture.BaseUrl = "Foobar";
            fixture.Token = "foo";
            fixture.OkButton.CanExecute(null).Should().BeFalse();

            fixture.BaseUrl = "ftp://google.com";
            fixture.OkButton.CanExecute(null).Should().BeFalse();

            fixture.BaseUrl = "    ";
            fixture.OkButton.CanExecute(null).Should().BeFalse();

            fixture.BaseUrl = "http://$#%(@#$)@#!!)@(";
            fixture.OkButton.CanExecute(null).Should().BeFalse();

            fixture.BaseUrl = "http://foobar";
            fixture.OkButton.CanExecute(null).Should().BeTrue();
        }
        static ISearchViewModel setupStandardFixture(MoqMockingKernel kernel, IRoutingState router = null)
        {
            router = router ?? new RoutingState();
            kernel.Bind<ISearchViewModel>().To<SearchViewModel>();
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("UserAccount");
            kernel.Bind<IBlobCache>().To<TestBlobCache>().Named("LocalMachine");

            kernel.GetMock<IPlayApi>().Setup(x => x.Search("Foo"))
                .Returns(Observable.Return(new List<Song>() { Fakes.GetSong() }))
                .Verifiable();

            kernel.GetMock<ILoginMethods>().Setup(x => x.CurrentAuthenticatedClient).Returns(kernel.Get<IPlayApi>());
            kernel.GetMock<IScreen>().Setup(x => x.Router).Returns(router);

            var img = new BitmapImage();
            kernel.GetMock<IPlayApi>().Setup(x => x.FetchImageForAlbum(It.IsAny<Song>()))
                .Returns(Observable.Return(img))
                .Verifiable();

            RxApp.ConfigureServiceLocator((t,s) => kernel.Get(t,s), (t,s) => kernel.GetAll(t,s));

            var fixture = kernel.Get<ISearchViewModel>();
            return fixture;
        }
        public void SuccessfulLoginShouldActuallyLogIn()
        {
            var mock = new MoqMockingKernel();
            mock.Bind<ILoginViewModel>().To(typeof(LoginViewModel));

            mock.Bind<Func<IObservable<Unit>>>()
                .ToConstant<Func<IObservable<Unit>>>(() => Observable.Return(Unit.Default))
                .Named("confirmUserPass");

            var fixture = mock.Get<ILoginViewModel>();

            fixture.User = "******";
            fixture.Password = "******";

            fixture.Confirm.CanExecute(null).Should().BeTrue();

            Tuple<string, string> result = null;
            MessageBus.Current.Listen<Tuple<string, string>>("login").Subscribe(x => result = x);
            fixture.Confirm.Execute(null);

            result.Should().NotBeNull();
            result.Item1.Should().Be(fixture.User);
            result.Item2.Should().Be(fixture.Password);
        }
        public void SucceededLoginSetsTheCurrentAuthenticatedClient()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IWelcomeViewModel>().To<WelcomeViewModel>();

            string expectedUser = "******";
            string expectedUrl = "http://bar";

            kernel.Bind<Func<string, string, IObservable<Unit>>>()
                .ToConstant<Func<string, string, IObservable<Unit>>>((url, user) => Observable.Return<Unit>(Unit.Default))
                .Named("connectToServer");

            var mock = kernel.GetMock<IScreen>();
            var routingState = new RoutingState();
            mock.Setup(x => x.Router).Returns(routingState);

            kernel.Bind<IScreen>().ToConstant(mock.Object);

            var initialPage = kernel.Get<IRoutableViewModel>();
            kernel.Get<IScreen>().Router.NavigateAndReset.Execute(initialPage);

            var cache = new TestBlobCache(null, (IEnumerable<KeyValuePair<string, byte[]>>)null);
            kernel.Bind<ISecureBlobCache>().ToConstant(cache);

            var fixture = kernel.Get<IWelcomeViewModel>();
            kernel.Get<IScreen>().Router.Navigate.Execute(fixture);

            bool errorThrown = false;
            using (UserError.OverrideHandlersForTesting(ex => { errorThrown = true; return Observable.Return(RecoveryOptionResult.CancelOperation); })) {
                fixture.Token = expectedUser;
                fixture.BaseUrl = expectedUrl;
                fixture.OkButton.Execute(null);
            }

            errorThrown.Should().BeFalse();

            kernel.Get<IScreen>().Router.GetCurrentViewModel().Should().Be(initialPage);
            kernel.GetMock<ILoginMethods>().Verify(x => x.SaveCredentials(expectedUrl, expectedUser), Times.Once());
        }
        public void CantHitOkWhenFieldsAreBlank()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IWelcomeViewModel>().To<WelcomeViewModel>();

            var fixture = kernel.Get<IWelcomeViewModel>();

            String.IsNullOrWhiteSpace(fixture.BaseUrl).Should().BeTrue();
            String.IsNullOrWhiteSpace(fixture.Token).Should().BeTrue();

            fixture.OkButton.CanExecute(null).Should().BeFalse();

            fixture.BaseUrl = "http://www.example.com";
            fixture.OkButton.CanExecute(null).Should().BeFalse();

            fixture.Token = "foo";
            fixture.OkButton.CanExecute(null).Should().BeTrue();
        }
        public void LoginFailureIntegrationTest()
        {
            var mock = new MoqMockingKernel();

            mock.Bind<ILoginViewModel>().To(typeof(LoginViewModel));

            var fixture = mock.Get<ILoginViewModel>() as LoginViewModel;
            fixture.User = "******";
            fixture.Password = "******";

            fixture.TestUserNameAndPassword().Select(_ => false)
                .Catch(Observable.Return(true))
                .Timeout(TimeSpan.FromSeconds(10), RxApp.TaskpoolScheduler)
                .First()
                .Should().BeTrue();
        }
        IPlayViewModel setupStandardMock(MoqMockingKernel kernel, IRoutingState router, Action extraSetup = null)
        {
            kernel.Bind<IPlayViewModel>().To<PlayViewModel>();

            var playApi = kernel.GetMock<IPlayApi>();
            playApi.Setup(x => x.ListenUrl()).Returns(Observable.Never<string>());
            playApi.Setup(x => x.ConnectToSongChangeNotifications()).Returns(Observable.Never<Unit>());
            playApi.Setup(x => x.NowPlaying()).Returns(Observable.Return(Fakes.GetSong()));
            playApi.Setup(x => x.Queue()).Returns(Observable.Return(Fakes.GetAlbum()));
            playApi.Setup(x => x.FetchImageForAlbum(It.IsAny<Song>())).Returns(Observable.Return<BitmapImage>(null));

            kernel.GetMock<IScreen>().Setup(x => x.Router).Returns(router);

            kernel.GetMock<ILoginMethods>()
                .Setup(x => x.EraseCredentialsAndNavigateToLogin())
                .Callback(() => router.Navigate.Execute(kernel.Get<IWelcomeViewModel>()));

            kernel.GetMock<ILoginMethods>()
                .Setup(x => x.CurrentAuthenticatedClient)
                .Returns(kernel.Get<IPlayApi>());

            if (extraSetup != null) extraSetup();

            RxApp.ConfigureServiceLocator((t,s) => kernel.Get(t,s), (t,s) => kernel.GetAll(t,s));
            return kernel.Get<IPlayViewModel>();
        }
        public void FailedLoginIsAUserError()
        {
            var kernel = new MoqMockingKernel();
            kernel.Bind<IWelcomeViewModel>().To<WelcomeViewModel>();

            kernel.Bind<Func<string, string, IObservable<Unit>>>()
                .ToConstant<Func<string, string, IObservable<Unit>>>((url, user) => Observable.Throw<Unit>(new Exception()))
                .Named("connectToServer");

            var fixture = kernel.Get<IWelcomeViewModel>();

            bool errorThrown = false;
            using (UserError.OverrideHandlersForTesting(ex => { errorThrown = true; return Observable.Return(RecoveryOptionResult.CancelOperation); })) {
                fixture.Token = "Foo";
                fixture.BaseUrl = "http://bar";
                fixture.OkButton.Execute(null);
            }

            errorThrown.Should().BeTrue();
        }