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>());
        }
        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 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);
            });
        }
        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 LoginScenarioRoutingTest()
        {
            var mock = new MoqMockingKernel();
            mock.Bind<ILoginViewModel>().To<LoginViewModel>();

            // Fake out the actual login code that makes sure the password is right
            mock.Bind<Func<IObservable<Unit>>>()
                .ToConstant<Func<IObservable<Unit>>>(() => Observable.Return(Unit.Default))
                .Named("confirmUserPass");

            var fixture = new AppViewModel(mock);

            // Our app starts on the Login page by default
            this.Log().Info("Current Route: {0}", fixture.Router.GetUrlForCurrentRoute());
            var loginModel = fixture.Router.GetCurrentViewModel() as ILoginViewModel;
            loginModel.Should().NotBeNull();

            // Put in a fake user/pass and hit the Ok button
            loginModel.User = "******";
            loginModel.Password = "******";
            loginModel.Confirm.Execute(null);

            // Make sure we're now showing the repo page
            this.Log().Info("Current Route: {0}", fixture.Router.GetUrlForCurrentRoute());
            (fixture.Router.GetCurrentViewModel() is IRepoSelectionViewModel).Should().BeTrue();
        }
Beispiel #6
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();
            }
        }
        internal static Mock<IPipelineHead> Initialize(MoqMockingKernel kernel)
        {
            var component = kernel.GetMock<IPipelineHead>();
            component.Setup(
                mock =>
                    mock.Run(It.IsAny<CancellationToken>())).Returns(new PipelinePayload
                    {
                        EgestSettings = new Pledge.Common.SerializableDictionary<string, string>
                        {
                            { "Name", "Egest"}
                        },
                        IngestSettings = new Pledge.Common.SerializableDictionary<string, string>
                        {
                            { "Name", "Ingest"}
                        },
                        PledgeResult = new PledgeResult
                        {
                            FileHasInvalidRecords = true,
                            FileHasValidRecords = true,
                            TotalFailedRecordsCount = 200,
                            TotalPassedRecordsCount = 300,
                            TotalRecordsProcessed = 500
                        }
                    });

            return component;
        }
Beispiel #8
0
 public void TearDownMockRepository()
 {
     this.mockRepository.VerifyAll();
     this.mockRepository = null;
     this.MockServiceLocator = null;
     this.kernel = null;
 }
        public BrokerRouterProxy(MoqMockingKernel kernel)
        {
            _kernel = kernel;

            //setup mock IKafkaConnection
            _fakeConn0 = new FakeKafkaConnection(new Uri("http://localhost:1"));
            _fakeConn0.ProduceResponseFunction = async () => new ProduceResponse { Offset = _offset0++, PartitionId = 0, Topic = TestTopic };
            _fakeConn0.MetadataResponseFunction = () => MetadataResponse();
            _fakeConn0.OffsetResponseFunction = async () => new OffsetResponse { Offsets = new List<long> { 0, 99 }, PartitionId = 0, Topic = TestTopic };
            _fakeConn0.FetchResponseFunction = async () => { Thread.Sleep(500); return null; };

            _fakeConn1 = new FakeKafkaConnection(new Uri("http://localhost:2"));
            _fakeConn1.ProduceResponseFunction = async () => new ProduceResponse { Offset = _offset1++, PartitionId = 1, Topic = TestTopic };
            _fakeConn1.MetadataResponseFunction = () => MetadataResponse();
            _fakeConn1.OffsetResponseFunction = async () => new OffsetResponse { Offsets = new List<long> { 0, 100 }, PartitionId = 1, Topic = TestTopic };
            _fakeConn1.FetchResponseFunction = async () => { Thread.Sleep(500); return null; };

            _mockKafkaConnectionFactory = _kernel.GetMock<IKafkaConnectionFactory>();
            _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is<KafkaEndpoint>(e => e.Endpoint.Port == 1), It.IsAny<TimeSpan>(), It.IsAny<IKafkaLog>(), It.IsAny<int>(), It.IsAny<TimeSpan?>(), It.IsAny<StatisticsTrackerOptions>())).Returns(() => _fakeConn0);
            _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is<KafkaEndpoint>(e => e.Endpoint.Port == 2), It.IsAny<TimeSpan>(), It.IsAny<IKafkaLog>(), It.IsAny<int>(), It.IsAny<TimeSpan?>(), It.IsAny<StatisticsTrackerOptions>())).Returns(() => _fakeConn1);
            _mockKafkaConnectionFactory.Setup(x => x.Resolve(It.IsAny<Uri>(), It.IsAny<IKafkaLog>()))
                .Returns<Uri, IKafkaLog>((uri, log) => new KafkaEndpoint
                {
                    Endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), uri.Port),
                    ServeUri = uri
                });
        }
Beispiel #10
0
 internal static Mock<IBuilder> Initialize(MoqMockingKernel kernel)
 {
     _concreteBuilder = new ModelBuilder();
     var mockBuilder = kernel.GetMock<IBuilder>();
     mockBuilder.Setup(mock => mock.CreatePipeline(It.IsAny<IRemoteJob>(), It.IsAny<IConfiguration>())).
         Returns<IRemoteJob, IConfiguration>((arg1, arg2) => _concreteBuilder.CreatePipeline(arg1, arg2));
     return mockBuilder;
 }
        public void QueuingASongShouldCallPlayApi()
        {
            var kernel = new MoqMockingKernel();
            var song = Fakes.GetSong();
            var fixture = setupStandardFixture(song, kernel);

            fixture.QueueSong.Execute(null);
            kernel.GetMock<IPlayApi>().Verify(x => x.QueueSong(It.IsAny<Song>()));
        }
        internal static Mock<IPipelineMember> Initialize(MoqMockingKernel kernel)
        {
            var component = kernel.GetMock<IPipelineMember>();
            component.Setup(
                mock =>
                    mock.AddRecord(It.IsAny<IRecord>())).Verifiable();
            component.Setup(mock => mock.EndPipeline()).Verifiable();

            return component;
        }
Beispiel #13
0
        public void InternalTearDown()
        {
            TearDown();

            if (_container != null)
            {
                _container.Dispose ();
                _container = null;
            }
        }
        public void NavigatingToPlayWithCredsShouldStayOnPlay()
        {
            var kernel = new MoqMockingKernel();
            var router = new RoutingState();

            var fixture = setupStandardMock(kernel, router);

            router.Navigate.Execute(fixture);
            (router.GetCurrentViewModel() is IPlayViewModel).Should().BeTrue();
        }
        public void EnsureWeFetchAnAlbumCover()
        {
            var kernel = new MoqMockingKernel();
            var fixture = setupStandardFixture(kernel);

            fixture.SearchQuery = "Foo";
            fixture.PerformSearch.Execute(null);

            kernel.GetMock<IPlayApi>().Verify(x => x.Search("Foo"), Times.Once());
            kernel.GetMock<IPlayApi>().Verify(x => x.FetchImageForAlbum(It.IsAny<Song>()), Times.Once());
        }
        public void LogoutButtonShouldSendMeToWelcomePage()
        {
            var kernel = new MoqMockingKernel();
            var router = new RoutingState();

            var fixture = setupStandardMock(kernel, router);
            router.Navigate.Execute(fixture);
            fixture.Logout.Execute(null);

            (router.GetCurrentViewModel() is IPlayViewModel).Should().BeFalse();
        }
Beispiel #17
0
 public void SetupMockRepository()
 {
     // MockBehavior.Strict says "I have to impliment every use"
     // DefaultValue.Mock means "recursive fakes"
     NinjectSettings settings = new NinjectSettings();
     settings.SetMockBehavior( MockBehavior.Strict );
     this.kernel = new MoqMockingKernel( settings );
     this.mockRepository = this.kernel.MockRepository;
     this.mockRepository.DefaultValue = DefaultValue.Mock;
     this.MockServiceLocator = new MockServiceLocator( this.kernel );
 }
        public void DontThrashPlayApiOnMultipleSearchCalls()
        {
            var kernel = new MoqMockingKernel();
            var fixture = setupStandardFixture(kernel);

            fixture.SearchQuery = "Foo";
            fixture.PerformSearch.Execute(null);
            fixture.PerformSearch.Execute(null);
            fixture.PerformSearch.Execute(null);

            kernel.GetMock<IPlayApi>().Verify(x => x.Search("Foo"), Times.Once());
        }
        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());
            }
        }
Beispiel #20
0
 // ReSharper disable once UnusedMember.Global
 public void InitializeMocks()
 {
     _kernel = new MoqMockingKernel();
     FakeSecurity = FakeApi.Initialize(_kernel);
     FakeRepository = Moq.FakeRepository.Initialize(_kernel);
     FakeConfigurationManager = Moq.FakeConfigurationManager.Initialize(_kernel);
     FakePledgeManager = Moq.FakePledgeManager.Initialize(_kernel);
     FakeBuilder = Moq.FakeBuilder.Initialize(_kernel);
     FakeAuditingClient = FakeAuditorRestClient.Initialize(_kernel);
     FakeUserGroupManager = Moq.FakeUserGroupManager.Initialize(_kernel);
     FakeAuditor = Moq.FakeAuditor.Initialize(_kernel);
 }
        public void MockRepositoryCanBeAccessed()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Components.RemoveAll<IMockRepositoryProvider>();
                kernel.Components.Add<IMockRepositoryProvider, TestMockRepositoryProvider>();
                var repository = new MockRepository(MockBehavior.Default);
                TestMockRepositoryProvider.Repository = repository;

                kernel.MockRepository.Should().BeSameAs(repository);
            }
        }
        internal static Mock<IUserGroupManager> Initialize(MoqMockingKernel kernel)
        {
            CreateUsers();
            Reload();

            var repository = kernel.GetMock<IUserGroupManager>();
            repository.Setup(mock => mock.AddMember(IdGroupB, It.IsAny<string>())).Callback<Guid, string>(AddUser);
            repository.Setup(mock => mock.CreateUserGroup(It.IsAny<string>())).Callback<string>(CreateGroup);
            repository.Setup(mock => mock.GetGroupMembers(It.IsAny<Guid>())).Returns<Guid>(GetGroupMembers);
            repository.Setup(mock => mock.RemoveMembers(It.IsAny<Guid>(), It.IsAny<List<Guid>>())).Callback<Guid, List<Guid>>(RemoveUsers);

            return repository;
        }
Beispiel #23
0
        internal static Mock<IPledge> Initialize(MoqMockingKernel kernel)
        {
            SuccessPledgeResult = new PledgeResult { FileHasValidRecords = true, TotalRecordsProcessed = 3};
            FailPledgeResult = new PledgeResult { FileHasInvalidRecords = true, TotalRecordsProcessed = 3 };
            PartialPledgeResult = new PledgeResult { FileHasValidRecords = true, FileHasInvalidRecords = true, TotalRecordsProcessed = 3 };

            var pledge = kernel.GetMock<IPledge>();
            pledge.Setup(
                mock =>
                    mock.Run(FakeConfigurationManager.Configuration, It.IsAny<IRemoteJob>(),It.IsAny<string>())).Returns(SuccessPledgeResult);

            return pledge;
        }
 public void Setup()
 {
     _kernel = new MoqMockingKernel();
     _mockKafkaConnection1 = _kernel.GetMock<IKafkaConnection>();
     _mockKafkaConnectionFactory = _kernel.GetMock<IKafkaConnectionFactory>();
     _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is<KafkaEndpoint>(e => e.Endpoint.Port == 1), It.IsAny<TimeSpan>(),
                 It.IsAny<IKafkaLog>(), It.IsAny<int>(), It.IsAny<TimeSpan?>(), It.IsAny<StatisticsTrackerOptions>())).Returns(() => _mockKafkaConnection1.Object);
     _mockKafkaConnectionFactory.Setup(x => x.Resolve(It.IsAny<Uri>(), It.IsAny<IKafkaLog>()))
         .Returns<Uri, IKafkaLog>((uri, log) => new KafkaEndpoint
         {
             Endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), uri.Port),
             ServeUri = uri
         });
 }
Beispiel #25
0
        internal static Mock<IPledgeAuditor> Initialize(MoqMockingKernel kernel)
        {
            _logs = new List<PledgeLog>();
            var auditor = kernel.GetMock<IPledgeAuditor>();
            auditor.Setup(mock => mock.Log(It.IsAny<PledgeLog>())).Callback<PledgeLog>(LogEntry);
            auditor.Setup(mock => mock.Log(It.IsAny<List<PledgeLog>>())).Callback<IEnumerable<PledgeLog>>(LogEntries);
            auditor.Setup(mock => mock.SaveLogs()).Callback(SaveLogs);
            auditor.Setup(mock => mock.CreateFileProcessPledgeLog(It.IsAny<IConfiguration>(), It.IsAny<IRemoteJob>(), It.IsAny<Dictionary<string, string>>()))
                .Returns<IConfiguration, IRemoteJob, Dictionary<string, string>>(CreateFileProcessPledgeLog);

            auditor.Setup(mock => mock.GetAllByUserName(It.IsAny<string>(), It.IsAny<LogType>(),
                It.IsAny<int>(), It.IsAny<int>(), It.IsAny<bool>())).Returns<string, LogType, int, int, bool>(GetForUser);

            return auditor;
        }
        public void PlayApiShouldBeCalledOnPerformSearch()
        {
            var kernel = new MoqMockingKernel();
            var fixture = setupStandardFixture(kernel);
            fixture.PerformSearch.CanExecute(null).Should().BeFalse();

            fixture.SearchQuery = "Foo";
            fixture.PerformSearch.CanExecute(null).Should().BeTrue();
            fixture.PerformSearch.Execute(null);

            kernel.GetMock<IPlayApi>().Verify(x => x.Search("Foo"), Times.Once());

            fixture.SearchResults.Count.Should().Be(1);
            fixture.SearchResults[0].Model.id.Should().Be("4B52884E1E293890");
        }
        public void Setup()
        {
            _kernel = new MoqMockingKernel();

            //setup mock IKafkaConnection
            _mockPartitionSelector      = _kernel.GetMock <IPartitionSelector>();
            _mockKafkaConnection1       = _kernel.GetMock <IKafkaConnection>();
            _mockKafkaConnectionFactory = _kernel.GetMock <IKafkaConnectionFactory>();
            _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is <KafkaEndpoint>(e => e.Endpoint.Port == 1), It.IsAny <TimeSpan>(), It.IsAny <IKafkaLog>(), null)).Returns(() => _mockKafkaConnection1.Object);
            _mockKafkaConnectionFactory.Setup(x => x.Resolve(It.IsAny <Uri>(), It.IsAny <IKafkaLog>()))
            .Returns <Uri, IKafkaLog>((uri, log) => new KafkaEndpoint
            {
                Endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), uri.Port),
                ServeUri = uri
            });
        }
Beispiel #28
0
        public void SetUpKernel()
        {
            if (!TestFrameworkConfiguration.UserSetupLoaded)
            {
                LoadUserSetup();
            }

            var settings = new NinjectSettings
            {
                AllowNullInjection = true
            };

            kernel = new MoqMockingKernel(settings);

            kernel.Settings.SetMockBehavior(TestFrameworkConfiguration.DefaultMockBehavior);
        }
Beispiel #29
0
        public void SetupMockRepository()
        {
            // MockBehavior.Strict says "I have to impliment every use"
            // DefaultValue.Mock means "recursive fakes"
            MockBehavior mockBehavior = MockBehavior.Strict;
            DefaultValue defaultValue = DefaultValue.Mock;

            // Ninject, why you gotta make this so hard?
            NinjectSettings settings = new NinjectSettings();
            settings.SetMockBehavior( mockBehavior );
            MoqMockingKernel kernel = new MoqMockingKernel( settings );
            kernel.MockRepository.DefaultValue = defaultValue;

            // Initialize the mock service locator
            this.MockServiceLocator = new MockServiceLocator( kernel, mockBehavior );
        }
Beispiel #30
0
        public RegisterV1ControllerTests()
        {
            this.kernel = new MoqMockingKernel();
            // Repository
            this.kernel.Bind <CrossoverLoggerContext>().ToMock().InSingletonScope();
            this.kernel.Bind <IApplicationRepository>().ToMock().InSingletonScope();
            this.kernel.Bind <IRateLimitRepository>().ToMock().InSingletonScope();
            this.kernel.Bind <ILogRepository>().ToMock().InSingletonScope();
            this.kernel.Bind <ITokenRepository>().ToMock().InSingletonScope();

            // Service
            this.kernel.Bind <IApplicationService>().To <ApplicationService>();
            this.kernel.Bind <IRateLimitService>().To <RateLimitService>();
            this.kernel.Bind <ILogService>().To <LogService>();
            this.kernel.Bind <ITokenService>().To <TokenService>();
        }
Beispiel #31
0
        public void GetUserByUserNameAndPassword_Should_Fail()
        {
            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.GetUserByUserNameAndPassword("Login", "Haslo");

                result.ShouldBeNull();
            }
        }
        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 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 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();
        }
        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();
        }
Beispiel #37
0
        public void AccountCancellation_Given_ModelFailure_Should_ReturnFailureModel()
        {
            //Arrange
            var mockingKernel = new MoqMockingKernel();
            var mockConfig    = mockingKernel.GetMock <IConfig>();

            mockConfig.SetupGet(p => p.SimfyBaseUrl).Returns("SimfyBaseUrl");
            mockConfig.SetupGet(p => p.SimfyApiUsername).Returns("SimfyApiUsername");
            mockConfig.SetupGet(p => p.SimfyApiPassword).Returns("SimfyApiPassword");
            mockConfig.SetupGet(p => p.SimfyEmail).Returns("SimfyEmail");
            var                 mockHttpUtility  = mockingKernel.GetMock <IHttpUtility>();
            var                 service          = new ThirdPartyServiceSimfy(mockingKernel);
            PrivateObject       privateObject    = new PrivateObject(service);
            var                 SimfyBaseUrl     = privateObject.GetFieldOrProperty("SimfyBaseUrl", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var                 SimfyApiUsername = privateObject.GetFieldOrProperty("SimfyApiUsername", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var                 SimfyApiPassword = privateObject.GetFieldOrProperty("SimfyApiPassword", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var                 SimfyEmail       = privateObject.GetFieldOrProperty("SimfyEmail", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var                 simfy            = SimfyBaseUrl.ToString() + "/unsubscribe";;
            HttpResponseMessage value            = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            var                 accountResponse  = new SimfyAccountCancellationResponse()
            {
                Success        = false,
                FailureReasons = new[]
                {
                    "Test Failed To Cancel Simfy Service"
                }
            };

            value.Content = new StringContent(JsonConvert.SerializeObject(accountResponse));
            var model = new SimfyAccountCancellationRequest();

            value.Content.Headers.Clear();
            value.Content.Headers.Add("Content-Type", "application/json");
            mockHttpUtility.Setup(p => p.PostRequest(simfy, "", model, null, false, 5))
            .Returns(value);
            //Act

            var responce = service.AccountCancellation(model);

            //Assert
            mockHttpUtility.Verify(p => p.PostRequest(simfy, "", model, null, false, 5), Times.Once);

            Assert.IsFalse(responce.IsSuccess);
            Assert.IsTrue(!string.IsNullOrEmpty(responce.Message));
        }
Beispiel #38
0
        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 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());
        }
Beispiel #40
0
        public void SimfyCancellation_Given_OrderItemIsNull_Expect_ValidationMessage()
        {
            //Arrange
            var kernel            = new MoqMockingKernel();
            var thirdPartyService = kernel.GetMock <IThirdPartyServiceSimfy>();
            var orderItemRepo     = kernel.GetMock <IRepositoryOrderItemData>();

            orderItemRepo.Setup(p => p.GetByOrderItemId(1))
            .Returns(new EnumerableQuery <OrderItemData>(new List <OrderItemData>()));
            ComponentSimfy componentSimfy = new ComponentSimfy(kernel);
            //Act
            var response = componentSimfy.SimfyCancellation(1);

            //Assert
            Assert.AreEqual("Order item data not found.", response.Message);
            Assert.IsFalse(response.IsSuccess);
            orderItemRepo.VerifyAll();
        }
Beispiel #41
0
        public void SimfyActivation_Given_NoOrderItemInRepo_Expect_ValidationMessage()
        {
            //Arrange
            var kernel            = new MoqMockingKernel();
            var thirdPartyService = kernel.GetMock <IThirdPartyServiceSimfy>();
            var orderItemRepo     = kernel.GetMock <IRepositoryOrderItemData>();

            orderItemRepo.Setup(p => p.IsOrderItemActivated(1))
            .Returns(true);
            ComponentSimfy componentSimfy = new ComponentSimfy(kernel);
            //Act
            var response = componentSimfy.SimfyActivation("password", "password", 1);

            //Assert
            Assert.AreEqual("No Order Item Data could be found.", response.Message);
            Assert.IsFalse(response.IsSuccess);
            orderItemRepo.Verify(p => p.IsOrderItemActivated(1), Times.Never);
        }
Beispiel #42
0
        public void NullFeedIsPassedThroughFromPhabricator()
        {
            var kernel = new MoqMockingKernel();

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

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

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

            Assert.IsType <FeedViewModel>(viewResult.Model);
            Assert.Null(((FeedViewModel)viewResult.Model).Feed);
        }
        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>()));
        }
Beispiel #44
0
        public void Delete_Should_Not_Delete_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

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

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

                var service = kernel.Get <PaymentService>();
                var input   = _paymentFaker.Generate(1).LastOrDefault();
                service.Delete(_mapper.Map <PaymentBasicViewModel>(input));

                data.Count.ShouldBe(5);
            }
        }
Beispiel #45
0
        public void AccountCreation_Given_Model_Should_SendPOSTRequest()
        {
            var mockingKernel = new MoqMockingKernel();

            //Arrange
            var mockConfig = mockingKernel.GetMock <IConfig>();

            mockConfig.SetupGet(p => p.SimfyBaseUrl).Returns("SimfyBaseUrl");
            mockConfig.SetupGet(p => p.SimfyApiUsername).Returns("SimfyApiUsername");
            mockConfig.SetupGet(p => p.SimfyApiPassword).Returns("SimfyApiPassword");
            mockConfig.SetupGet(p => p.SimfyEmail).Returns("SimfyEmail");

            var mockHttpUtility = mockingKernel.GetMock <IHttpUtility>();


            var           service          = new ThirdPartyServiceSimfy(mockingKernel);
            PrivateObject privateObject    = new PrivateObject(service);
            var           SimfyBaseUrl     = privateObject.GetFieldOrProperty("SimfyBaseUrl", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var           SimfyApiUsername = privateObject.GetFieldOrProperty("SimfyApiUsername", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var           SimfyApiPassword = privateObject.GetFieldOrProperty("SimfyApiPassword", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var           SimfyEmail       = privateObject.GetFieldOrProperty("SimfyEmail", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

            var model = new SimfyAccountCreateRequest();
            var simfy = SimfyBaseUrl.ToString() + "/create";;
            HttpResponseMessage          value           = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
            SimfyAccountCreationResponse accountResponse = new SimfyAccountCreationResponse();

            value.Content = new StringContent(JsonConvert.SerializeObject(accountResponse));
            value.Content.Headers.Clear();
            value.Content.Headers.Add("Content-Type", "application/json");

            mockHttpUtility.Setup(p => p.PostRequest(simfy, "", model, null, false, 5))
            .Returns(value);
            //Act

            service.AccountCreation(model);
            //Assert
            Assert.AreEqual(model.ApiLogin, SimfyApiUsername);
            Assert.AreEqual(model.ApiPassword, SimfyApiPassword);
            Assert.AreEqual(model.Email, model.MobileNumber + SimfyEmail);

            mockHttpUtility.Verify(p => p.PostRequest(simfy, "", model, null, false, 5), Times.Once);
        }
Beispiel #46
0
        public void Delete_Should_Not_Delete_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 mapper  = MapperService.GetMapperInstance();
                var input   = _itemFaker.Generate(6).LastOrDefault();
                service.Delete(_mapper.Map <ItemDetailViewModel>(input));

                data.Count.ShouldBe(5);
            }
        }
Beispiel #47
0
        public void WhenPusherFiresWeShouldUpdateTheAlbum()
        {
            var kernel = new MoqMockingKernel();
            var router = new RoutingState();
            var pusher = new Subject <Unit>();
            int nowPlayingExecuteCount = 0;

            var fixture = setupStandardMock(kernel, router, () => {
                kernel.GetMock <IPlayApi>().Setup(x => x.ConnectToSongChangeNotifications()).Returns(pusher);
                kernel.GetMock <IPlayApi>().Setup(x => x.NowPlaying())
                .Callback(() => nowPlayingExecuteCount++).Returns(Observable.Return(Fakes.GetSong()));
            });

            router.Navigate.Execute(fixture);
            nowPlayingExecuteCount.Should().Be(1);

            pusher.OnNext(Unit.Default);
            nowPlayingExecuteCount.Should().Be(2);
        }
Beispiel #48
0
        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 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();
        }
        private static void BindRetryManager(MoqMockingKernel kernel)
        {
            string retryStrategyName = "ExponentialBackoff";
            var    retryStrategy     = kernel.Get <RetryStrategy>(retryStrategyName);

            var retryStrategies = new List <RetryStrategy>()
            {
                kernel.Get <ExponentialBackoff>()
            };

            kernel.Bind <IEnumerable <RetryStrategy> >().ToConstant <List <RetryStrategy> >(retryStrategies).Named("RetryManagerStrategies");
            var retryStrategyNameMap = new Dictionary <string, string>();

            retryStrategyNameMap.Add(retryStrategyName, retryStrategyName);

            var retryManager = new CustomRetryManager(retryStrategies, retryStrategyName, retryStrategyNameMap);

            kernel.Bind <CustomRetryManager>().ToConstant(retryManager);
            RetryManager.SetDefault(retryManager);
        }
Beispiel #51
0
        public void Delete_Should_Delete_Properly()
        {
            using (var kernel = new MoqMockingKernel())
            {
                kernel.Load(new EntityFrameworkTestingMoqModule());

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

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

                var    service = kernel.Get <PaymentService>();
                var    input   = _mapper.Map <PaymentBasicViewModel>(service.Get(1));
                Action act     = () => { service.Delete(input); };
                Assert.ThrowsException <FileLoadException>(act);

                data.Count.ShouldBe(4);
                data.FirstOrDefault(x => x.ID == input.ID).ShouldBeNull();
            }
        }
        public void QueueingAlbumShouldCallQueueSongForEverySong()
        {
            var kernel = new MoqMockingKernel();
            var song   = Fakes.GetSong();

            var fakeAlbum   = Fakes.GetAlbum();
            var queuedSongs = new List <Song>();
            var fixture     = setupStandardFixture(song, kernel);

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

            fixture.QueueAlbum.Execute(null);

            this.Log().Info("Queued songs: {0}", String.Join(",", queuedSongs.Select(x => x.name)));
            queuedSongs.Count.Should().Be(fakeAlbum.Count);
            fakeAlbum.Zip(queuedSongs, (e, a) => e.id == a.id).All(x => x).Should().BeTrue();
        }
Beispiel #53
0
        public void Delete_Should_Delete_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    input   = service.Get(1);
                Action act     = () => { service.Delete(_mapper.Map <EmployeeDetailViewModel>(input)); };
                Assert.ThrowsException <FileLoadException>(act);

                data.Count.ShouldBe(4);
                data.FirstOrDefault(x => x.Login == input.Login).ShouldBeNull();
            }
        }
Beispiel #54
0
        public void AccountCreation_Given_HTTPRequestException_Should_CatchException()
        {
            //Arrange
            var mockingKernel = new MoqMockingKernel();
            var mockConfig    = mockingKernel.GetMock <IConfig>();

            mockConfig.SetupGet(p => p.SimfyBaseUrl).Returns("SimfyBaseUrl");
            mockConfig.SetupGet(p => p.SimfyApiUsername).Returns("SimfyApiUsername");
            mockConfig.SetupGet(p => p.SimfyApiPassword).Returns("SimfyApiPassword");
            mockConfig.SetupGet(p => p.SimfyEmail).Returns("SimfyEmail");
            var           mockHttpUtility  = mockingKernel.GetMock <IHttpUtility>();
            var           service          = new ThirdPartyServiceSimfy(mockingKernel);
            PrivateObject privateObject    = new PrivateObject(service);
            var           SimfyBaseUrl     = privateObject.GetFieldOrProperty("SimfyBaseUrl", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var           SimfyApiUsername = privateObject.GetFieldOrProperty("SimfyApiUsername", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var           SimfyApiPassword = privateObject.GetFieldOrProperty("SimfyApiPassword", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            var           SimfyEmail       = privateObject.GetFieldOrProperty("SimfyEmail", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);

            var model = new SimfyAccountCreateRequest();

            var simfy = SimfyBaseUrl.ToString() + "/create";;
            HttpResponseMessage          value           = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError);
            SimfyAccountCreationResponse accountResponse = new SimfyAccountCreationResponse()
            {
                Success = true
            };

            value.Content = new StringContent(JsonConvert.SerializeObject(accountResponse));
            value.Content.Headers.Clear();
            value.Content.Headers.Add("Content-Type", "application/json");
            mockHttpUtility.Setup(p => p.PostRequest(simfy, "", model, null, false, 5))
            .Throws <Exception>();
            //Act

            var responce = service.AccountCreation(model);

            //Assert
            mockHttpUtility.Verify(p => p.PostRequest(simfy, "", model, null, false, 5), Times.Once);
            Assert.IsFalse(responce.IsSuccess);
            Assert.AreEqual("Exception: Creating Simfy Account.", responce.Message);
        }
Beispiel #55
0
        public void AddToCancellationQueue_Given_NoProvidersExist_Expect_ExceptionMessage()
        {
            var kernel = new MoqMockingKernel();
            var workflowStorageComponent = kernel.GetMock <IWorkflowStorageComponent>();
            var providerMock             = kernel.GetMock <IRepositoryProvider>();

            int orderItemId = 666;
            int providerId  = 1;

            workflowStorageComponent.Setup(p => p.PopulateBillingCancelQueue(It.IsAny <BillingExtractState>()))
            .Throws <Exception>();
            ComponentOrderCancellation componentOrderAddToCancelQueue = new ComponentOrderCancellation(kernel);
            //Act
            var response = componentOrderAddToCancelQueue.AddToCancellationQueue(orderItemId, providerId);

            //Assert
            Assert.AreEqual("Exception: Adding Cancellation to Billing Cancel Queue", response.Message);
            Assert.IsFalse(response.IsSuccess);
            workflowStorageComponent.VerifyAll();
            providerMock.Verify(p => p.GetNameByProviderId(providerId), Times.Once);
        }
Beispiel #56
0
        public static void Bind(MoqMockingKernel _kernel)
        {
            //BranchReceipt
            _kernel.Bind <Interfaces.IBranchReceiptBS>().To <BranchReceiptBS>();
            _kernel.Bind <Interfaces.IBranchReceiptDS>().To <BranchReceiptDataService>();

            //BranchSales
            _kernel.Bind <Interfaces.IBranchSalesBS>().To <BranchSalesBS>();
            _kernel.Bind <Interfaces.IBranchSalesDS>().To <BranchSalesDataService>();

            //Invoice
            _kernel.Bind <Interfaces.IInvoiceBS>().To <InvoiceBS>();
            _kernel.Bind <Interfaces.IInvoiceDS>().To <InvoiceDataService>();

            //MemberReceipt
            _kernel.Bind <Interfaces.IMemberReceiptBS>().To <MemberReceiptBS>();
            _kernel.Bind <Interfaces.IMemberReceiptDS>().To <MemberReceiptDataService>();

            //MemberPayroll
            _kernel.Bind <Interfaces.IMemberPayrollBS>().To <MemberPayrollBS>();
            _kernel.Bind <Interfaces.IMemberPayrollDS>().To <MemberPayrollDataService>();
        }
Beispiel #57
0
        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();
        }
        public BrokerRouterProxy(MoqMockingKernel kernel)
        {
            _kernel = kernel;

            //setup mock IKafkaConnection
            _fakeConn0 = new FakeKafkaConnection(new Uri("http://localhost:1"));
            _fakeConn0.ProduceResponseFunction = async() => new ProduceResponse {
                Offset = _offset0++, PartitionId = 0, Topic = TestTopic
            };
            _fakeConn0.MetadataResponseFunction = () => MetadataResponse();
            _fakeConn0.OffsetResponseFunction   = async() => new OffsetResponse {
                Offsets = new List <long> {
                    0, 99
                }, PartitionId = 0, Topic = TestTopic
            };
            _fakeConn0.FetchResponseFunction = async() => { Thread.Sleep(500); return(null); };

            _fakeConn1 = new FakeKafkaConnection(new Uri("http://localhost:2"));
            _fakeConn1.ProduceResponseFunction = async() => new ProduceResponse {
                Offset = _offset1++, PartitionId = 1, Topic = TestTopic
            };
            _fakeConn1.MetadataResponseFunction = () => MetadataResponse();
            _fakeConn1.OffsetResponseFunction   = async() => new OffsetResponse {
                Offsets = new List <long> {
                    0, 100
                }, PartitionId = 1, Topic = TestTopic
            };
            _fakeConn1.FetchResponseFunction = async() => { Thread.Sleep(500); return(null); };

            _mockKafkaConnectionFactory = _kernel.GetMock <IKafkaConnectionFactory>();
            _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is <KafkaEndpoint>(e => e.Endpoint.Port == 1), It.IsAny <TimeSpan>(), It.IsAny <IKafkaLog>(), It.IsAny <int>(), It.IsAny <TimeSpan?>(), It.IsAny <StatisticsTrackerOptions>())).Returns(() => _fakeConn0);
            _mockKafkaConnectionFactory.Setup(x => x.Create(It.Is <KafkaEndpoint>(e => e.Endpoint.Port == 2), It.IsAny <TimeSpan>(), It.IsAny <IKafkaLog>(), It.IsAny <int>(), It.IsAny <TimeSpan?>(), It.IsAny <StatisticsTrackerOptions>())).Returns(() => _fakeConn1);
            _mockKafkaConnectionFactory.Setup(x => x.Resolve(It.IsAny <Uri>(), It.IsAny <IKafkaLog>()))
            .Returns <Uri, IKafkaLog>((uri, log) => new KafkaEndpoint
            {
                Endpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), uri.Port),
                ServeUri = uri
            });
        }
Beispiel #59
0
        public void Get_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.Get(1);

                result.ID.ShouldBe(input[1].ID);
                result.Amount.ShouldBe(input[1].Amount);
                result.ExchangeRate.ShouldBe(input[1].ExchangeRate);
                result.OrderID.ShouldBe(input[1].OrderID);
                result.PaymentDate.ShouldBe(input[1].PaymentDate);
                result.Currency.ShouldBe(input[1].Currency);
            }
        }
Beispiel #60
0
        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());
        }