C# (CSharp) Mock Code Examples

C# (CSharp) Mock - 30 примеров найдено. Это лучшие примеры C# (CSharp) кода для Mock, полученные из open source проектов. Вы можете ставить оценку каждому примеру, чтобы помочь нам улучшить качество примеров.
        protected void SetupSubject()
        {
            MockUpdatableAuth = new Mock<IUpdatable<UserAuthentication>>();

            _passwords = new Passwords();
            _translateUserUserAuth = new DataUserToAccountUserTranslator();

            _userAuthProvider = new UserAuthenticationProvider(
                _translateUserUserAuth
                , MockRetrievableUserByEmail.Object
                , MockRetrievableAuthyId.Object
                , MockUpdatableAuth.Object
                , MockCreatableAuth.Object
                , _passwords
                , MockDeletableAuth.Object);

            Subject = new UserAccountProvider(
                _userAuthProvider
                , MockCreateableUser.Object
                , MockRetrievableUserById.Object
                , MockRetrievableUserByEmail.Object
                , MockDeletableUser.Object
                , MockUpdateableUser.Object
                , _translateUserUserAuth
                , MockSystemTime.Object);
        }
        public void CallTest()
        {
            //Arrange
            var domainStatProjectState1 = new DomainStatProjectState() { Producer = ProductName.TaggerIPhone, IsSuccessfulUpload = true };
            var domainStatProjectState2 = new DomainStatProjectState() { Producer = ProductName.TaggerIPhone, IsSuccessfulUpload = false };
            var domainStatProjectState3 = new DomainStatProjectState() { Producer = "ProductName", IsSuccessfulUpload = true };

            var domainReport = new DomainReport();

            var statProjectDeletionFilter = new Mock<IStatProjectDeletionFilter>();

            var taggerIPhoneDeletionsFilter = new TaggerIPhoneDeletionsFilter();
            taggerIPhoneDeletionsFilter.Set(statProjectDeletionFilter.Object);

            //Act
            taggerIPhoneDeletionsFilter.Call(domainStatProjectState1, domainReport);
            taggerIPhoneDeletionsFilter.Call(domainStatProjectState2, domainReport);
            taggerIPhoneDeletionsFilter.Call(domainStatProjectState3, domainReport);

            //Assert
            Assert.AreEqual(1, domainReport.TaggerIPhoneDeletions);
            statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState1, domainReport), Times.Once());
            statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState2, domainReport), Times.Once());
            statProjectDeletionFilter.Verify(m => m.Call(domainStatProjectState3, domainReport), Times.Once());
        }
        public void GetAllShouldReturnTodos()
        {
            var data = new List<Todo>
            {
                new Todo {Id = 1},
                new Todo {Id = 2},
                new Todo {Id = 3},
            }.AsQueryable();

            var mockSet = new Mock<DbSet<Todo>>();
            mockSet.As<IQueryable<Todo>>().Setup(m => m.Provider).Returns(data.Provider);
            mockSet.As<IQueryable<Todo>>().Setup(m => m.Expression).Returns(data.Expression);
            mockSet.As<IQueryable<Todo>>().Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.As<IQueryable<Todo>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

            var mockContext = new Mock<ApplicationDbContext>();
            mockContext.Setup(c => c.Todos).Returns(mockSet.Object);

            var service = new TodoRepository(mockContext.Object);
            var todos = service.GetAll().ToList();

            Assert.AreEqual(3, todos.Count);
            Assert.AreEqual(1, todos[0].Id);
            Assert.AreEqual(2, todos[1].Id);
            Assert.AreEqual(3, todos[2].Id);
        }
Пример #4
0
        public void TestInitialize()
        {

            IFhirModel _fhirModel;
            FhirPropertyIndex _propIndex;
            ResourceVisitor _resourceVisitor;
            ElementIndexer _elementIndexer;
            var _indexStoreMock = new Mock<IIndexStore>();

            var spPatientName = new SearchParamDefinition() { Resource = "Patient", Name = "name", Description = @"A portion of either family or given name of the patient", Type = SearchParamType.String, Path = new string[] { "Patient.name", } };
            var searchParameters = new List<SearchParamDefinition> { spPatientName };
            var resources = new Dictionary<Type, string> { { typeof(Patient), "Patient" }, { typeof(HumanName), "HumanName" } };
            var enums = new List<Type>();
            //CK: I use real objects: saves me a lot of mocking and provides for a bit of integration testing.
            _fhirModel = new FhirModel(resources, searchParameters, enums);
            _propIndex = new FhirPropertyIndex(_fhirModel, new List<Type> { typeof(Patient), typeof(HumanName) });
            _resourceVisitor = new ResourceVisitor(_propIndex);
            _elementIndexer = new ElementIndexer(_fhirModel);

            //_indexStoreMock.Setup(ixs => ixs.Save(It.IsAny<IndexValue>))

            sutLimited = new IndexService(_fhirModel, _propIndex, _resourceVisitor, _elementIndexer, _indexStoreMock.Object);

            _fhirModel = new FhirModel(); //For this test I want all available types and searchparameters.
            _propIndex = new FhirPropertyIndex(_fhirModel);
            _resourceVisitor = new ResourceVisitor(_propIndex);
            _elementIndexer = new ElementIndexer(_fhirModel);

            sutFull = new IndexService(_fhirModel, _propIndex, _resourceVisitor, _elementIndexer, _indexStoreMock.Object);
        }
 public void IsInvalidWhen_UserName_MatchesExistingUser()
 {
     const string userName = "user@domain.tld";
     const string userDisplayName = "Bruce Wayne";
     const string personDisplayName = "Adam West";
     var command = new CreatePersonCommand
     {
         DisplayName = personDisplayName,
         UserName = userName,
     };
     var queryProcessor = new Mock<IProcessQueries>(MockBehavior.Strict);
     queryProcessor.Setup(m => m.Execute(It.Is<GetUserByNameQuery>(q => q.Name == command.UserName)))
         .Returns(new User { Person = new Person { DisplayName = userDisplayName, } });
     var validator = new CreatePersonValidator(queryProcessor.Object);
     var results = validator.Validate(command);
     results.IsValid.ShouldBeFalse();
     results.Errors.Count.ShouldBeInRange(1, int.MaxValue);
     var error = results.Errors.SingleOrDefault(e => e.PropertyName == "UserName");
     error.ShouldNotBeNull();
     // ReSharper disable PossibleNullReferenceException
     error.ErrorMessage.ShouldEqual(string.Format(
         ValidateUser.FailedBecauseNameMatchedEntity,
             userName));
     // ReSharper restore PossibleNullReferenceException
 }
        public void scenario_10()
        {
            var propertyUpgradeUoW = new Mock<IPropertyUpgradeUoW>();
            propertyUpgradeUoW.Setup(x => x.ProductTypeRepository.Get())
                .Returns(GetDomainProductTypes());
            var calculator = new CityStorageCalculator(propertyUpgradeUoW.Object);
            var cityStorage = GetCityStorage();
            cityStorage.CurrentInventory.First(x => x.ProductTypeId == 1).Quantity = 8;
            cityStorage.CurrentInventory.First(x => x.ProductTypeId == 2).Quantity = 8;
            cityStorage.CurrentInventory.First(x => x.ProductTypeId == 3).Quantity = 8;
            cityStorage.CurrentInventory.First(x => x.ProductTypeId == 4).Quantity = 8;
            var request = new CalculateStorageRequest
            {
                CityStorage = cityStorage,
                NewProductQuantities = new[]
                {
                    new SimGame.Handler.Entities.Product
                    {
                        ProductTypeId = 3,
                        Quantity = 2
                    },
                }
            };

            var ret = calculator.CalculateNewStorageAmounts(request);
            ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 4).Quantity.ShouldEqual(6);
            ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 3).Quantity.ShouldEqual(10);
            ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 2).Quantity.ShouldEqual(8);
            ret.CityStorage.CurrentInventory.First(x => x.ProductTypeId == 1).Quantity.ShouldEqual(8);
        }
 public void GetUnitOfWorkFactory_uses_same_session_factory_as_provider()
 {
     var factory = new Mock<ISessionFactory>();
     var provider = new HibernateDataServicesProvider(factory.Object);
     var unitOfWorkFactory = (HibernateUnitOfWorkFactory)provider.GetUnitOfWorkFactory();
     Assert.AreEqual(factory.Object, unitOfWorkFactory.SessionFactory);
 }
Пример #8
0
        public void ShouldReturnLogFactoryByName() {
            var logFactoryRegistry = new LogFactoryRegistry();
            var mylogger = new Mock<ITaskLogFactory>().Object;

            logFactoryRegistry.RegisterLogFactory("mylogger", mylogger);
            Assert.That(logFactoryRegistry.GetLogFactoryByName("mylogger"), Is.SameAs(mylogger));
        }
Пример #9
0
        public void ShouldReturnNameOfLogFactory() {
            var logFactoryRegistry = new LogFactoryRegistry();
            var mylogger = new Mock<ITaskLogFactory>().Object;

            logFactoryRegistry.RegisterLogFactory("mylogger", mylogger);
            Assert.That(logFactoryRegistry.FindNameForLogFactory(mylogger), Is.EqualTo("mylogger"));
        }
        public void When_a_navigation_button_is_clicked_the_associated_page_should_be_displayed()
        {
            this.testContainer = new UnityContainer();
            this.autoMocker = new AutoMoq.AutoMoqer(this.testContainer);

            var mockPageViewModel = new Mock<IPageViewModel>();
            mockPageViewModel.SetupGet(page => page.Title).Returns("Page1");
            IPageViewModel pageViewModel = mockPageViewModel.Object;

            var viewModelFactoryMock = new Mock<IViewModelFactory>();
            viewModelFactoryMock.Setup(f => f.Get<StartPageViewModel>()).Returns(() => new StartPageViewModel(new Mock<INavigationService>().Object));
            this.autoMocker.SetInstance(viewModelFactoryMock.Object);

            var navigationServiceMock = this.navigationServiceMock;
            navigationServiceMock.Setup(vm => vm.GetDefaultPagesByNames())
                                 .Returns(
                                     new Dictionary<string, Func<IPageViewModel>>
                                         {
                                             { "page1", () => pageViewModel },
                                             { "page2", () => null },
                                             { "page3", () => null },
                                             { "page4", () => null },
                                         });

            INavigationService navigationService = navigationServiceMock.Object;
            this.autoMocker.SetInstance(navigationService);

            var applicationViewModel = this.autoMocker.Resolve<ApplicationViewModel>();

            applicationViewModel.LeftNavigationButtonCollection.Single(btn => btn.DisplayText == "page1").ExecuteAsync(null);

            navigationServiceMock.VerifySet(ns => ns.CurrentPage = pageViewModel);
        }
Пример #11
0
        public void ResolveDependenciesForInstallPackageResolvesDependencyUsingDependencyProvider()
        {
            // Arrange            
            IPackage packageA = PackageUtility.CreatePackage("A",
                                                            "1.0",
                                                             dependencies: new List<PackageDependency> {
                                                                 new PackageDependency("B")
                                                             });
            IPackage packageB = PackageUtility.CreatePackage("B");
            var repository = new Mock<PackageRepositoryBase>();
            repository.Setup(c => c.GetPackages()).Returns(new[] { packageA }.AsQueryable());
            var dependencyProvider = repository.As<IDependencyResolver>();
            dependencyProvider.Setup(c => c.ResolveDependency(It.Is<PackageDependency>(p => p.Id == "B"), It.IsAny<IPackageConstraintProvider>(), false, true, DependencyVersion.Lowest))
                              .Returns(packageB).Verifiable();
            var localRepository = new MockPackageRepository();

            IPackageOperationResolver resolver = new InstallWalker(localRepository,
                                                             repository.Object,
                                                             NullLogger.Instance,
                                                             ignoreDependencies: false,
                                                             allowPrereleaseVersions: false);


            // Act
            var operations = resolver.ResolveOperations(packageA).ToList();

            // Assert
            Assert.Equal(2, operations.Count);
            Assert.Equal(PackageAction.Install, operations.First().Action);
            Assert.Equal(packageB, operations.First().Package);
            Assert.Equal(PackageAction.Install, operations.Last().Action);
            Assert.Equal(packageA, operations.Last().Package);

            dependencyProvider.Verify();
        }
        public async Task Run_WhenCheckerThrows_FailureResult()
        {
            // Arrange
            var checkerMocks = Enumerable
                .Range(1, 3)
                .Select(x =>
                {
                    var mock = new Mock<IChecker>();
                    mock.SetupGet(y => y.Name).Returns(x.ToString());
                    mock.Setup(y => y.Check()).ThrowsAsync(new Exception("error " + mock.Object.Name));
                    return mock;
                })
                .ToArray();
            var healthCheck = new HealthCheck(checkerMocks.Select(x => x.Object));

            // Act
            var result = await healthCheck.Run();

            // Assert
            Assert.That(result.Passed, Is.False);
            Assert.That(result.Status, Is.EqualTo("failure"));
            Assert.That(result.Results.Length, Is.EqualTo(checkerMocks.Length));
            foreach (var checkerMock in checkerMocks)
            {
                var checkResult = result.Results.Single(x => x.Checker == checkerMock.Object.Name);
                Assert.That(checkResult.Checker, Is.EqualTo(checkerMock.Object.Name));
                Assert.That(checkResult.Passed, Is.False);
                Assert.That(checkResult.Output, Is.EqualTo("error " + checkerMock.Object.Name));
            }
        }
 public void ConnectControlViewModel_AddNewServer_ResourceRepositoryReturnExistingServers_False()
 {
     //------------Setup for test--------------------------
     var mainViewModel = new Mock<IMainViewModel>();
     var connectControlSingleton = new Mock<IConnectControlSingleton>();
     var env1 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false);
     var env2 = new TestEnvironmentModel(new Mock<IEventAggregator>().Object, Guid.NewGuid(), CreateConnection(true, false).Object, new Mock<IResourceRepository>().Object, false);
     var connectControlEnvironments = new ObservableCollection<IConnectControlEnvironment>();
     var controEnv1 = new Mock<IConnectControlEnvironment>();
     var controEnv2 = new Mock<IConnectControlEnvironment>();
     controEnv1.Setup(c => c.EnvironmentModel).Returns(env1);
     controEnv2.Setup(c => c.EnvironmentModel).Returns(env2);
     controEnv1.Setup(c => c.IsConnected).Returns(true);
     connectControlEnvironments.Add(controEnv2.Object);
     connectControlEnvironments.Add(controEnv1.Object);
     connectControlSingleton.Setup(c => c.Servers).Returns(connectControlEnvironments);
     var environmentRepository = new Mock<IEnvironmentRepository>();
     ICollection<IEnvironmentModel> environments = new Collection<IEnvironmentModel>
         {
             env1
         };
     environmentRepository.Setup(e => e.All()).Returns(environments);
     var viewModel = new ConnectControlViewModel(mainViewModel.Object, environmentRepository.Object, e => { }, connectControlSingleton.Object, "TEST : ", false);
     //------------Execution-------------------------------
     int serverIndex;
     var didAddNew = viewModel.AddNewServer(out serverIndex, i => { });
     //------------Assert----------------------------------
     Assert.IsNotNull(viewModel);
     Assert.IsFalse(didAddNew);
 }
        protected void Arrange()
        {
            var random = new Random();
            _subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
            _operationTimeout = TimeSpan.FromSeconds(30);
            _encoding = Encoding.UTF8;
            _disconnectedRegister = new List<EventArgs>();
            _errorOccurredRegister = new List<ExceptionEventArgs>();
            _channelDataEventArgs = new ChannelDataEventArgs(
                (uint)random.Next(0, int.MaxValue),
                new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });

            _sessionMock = new Mock<ISession>(MockBehavior.Strict);
            _channelMock = new Mock<IChannelSession>(MockBehavior.Strict);

            _sequence = new MockSequence();
            _sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
            _channelMock.InSequence(_sequence).Setup(p => p.Open());
            _channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);

            _subsystemSession = new SubsystemSessionStub(
                _sessionMock.Object,
                _subsystemName,
                _operationTimeout,
                _encoding);
            _subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
            _subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
            _subsystemSession.Connect();
        }
        public void GetAnonymousCompetitions()
        {
            var repository = new RepositoryForTests<Competition>();
            repository.TheContent.Add(new Competition
            {
                CompetitionType = CompetitionType.Field,
                Id = Guid.NewGuid(),
                IsPublic = true,
                Name = "Public1",
                StartDate = DateTime.Now,
                UseNorwegianCount = false
            });
            repository.TheContent.Add(new Competition
            {
                CompetitionType = CompetitionType.Field,
                Id = Guid.NewGuid(),
                IsPublic = false,
                Name = "Private1",
                StartDate = DateTime.Now,
                UseNorwegianCount = false
            });

            var rightsHelperMock = new Mock<IRightsHelper>();

            var userRolesInfoMock = new Mock<IRepository<UserRolesInfo>>();

            var competitions = new CompetitionsLogic(repository, userRolesInfoMock.Object, rightsHelperMock.Object);

            var result = competitions.GetCompetitions();
            Assert.AreEqual(1, result.Count());
        }
 public void MessagePassedToConstructorIsReturned()
 {
     const string Msg = "msg";
     var innerRule = new Mock<IRule<string>>();
     var rule = new NotRule<string>(innerRule.Object, Msg);
     Assert.AreEqual(Msg, rule.Message);
 }
Пример #17
0
        public static TestableChat GetTestableChat(string clientId, TrackingDictionary clientState, ChatUser user, NameValueCollection cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<IResourceProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            // setup client agent
            chat.Agent = new ClientAgent(mockedConnectionObject, "Chat");

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);

            // setup signal agent
            var prinicipal = new Mock<IPrincipal>();
            chat.Caller = new SignalAgent(mockedConnectionObject, clientId, "Chat", clientState);

            // setup context
            chat.Context = new HubContext(new HostContext(request.Object, null, prinicipal.Object), clientId);

            return chat;
        }
        public void Should_Return_Page_Html_Content()
        {
            // Create html content
            var htmlContent = TestDataProvider.CreateNewHtmlContent();
            var pageContent = TestDataProvider.CreateNewPageContent(htmlContent);
            htmlContent.Status = ContentStatus.Published;

            // Create command
            var command = new GetPageHtmlContentCommand();
            command.UnitOfWork = new Mock<IUnitOfWork>().Object;
            command.Repository = new Mock<IRepository>().Object;

            // Mock content service
            var serviceMock = new Mock<IContentService>();
            serviceMock
                .Setup(f => f.GetPageContentForEdit(pageContent.Id))
                .Returns(new Tuple<PageContent, Content>(pageContent, htmlContent));
            command.ContentService = serviceMock.Object;

            // Execute command
            var result = command.Execute(pageContent.Id);

            Assert.IsNotNull(result);
            Assert.AreEqual(result.Id, pageContent.Id);
            Assert.AreEqual(result.ContentId, htmlContent.Id);
            Assert.AreEqual(result.ContentName, htmlContent.Name);
            Assert.AreEqual(result.ContentVersion, htmlContent.Version);
            Assert.AreEqual(result.CurrentStatus, htmlContent.Status);
            Assert.AreEqual(result.PageId, pageContent.Page.Id);
            Assert.AreEqual(result.RegionId, pageContent.Region.Id);
            Assert.AreEqual(result.LiveFrom, htmlContent.ActivationDate);
            Assert.AreEqual(result.LiveTo, htmlContent.ExpirationDate);
        }
 public void GetCurrentSession_delegates_to_session_factory()
 {
     var factory = new Mock<ISessionFactory>();
     var provider = new HibernateDataServicesProvider(factory.Object);
     provider.GetCurrentSession();
     factory.Verify(sessionFactory => sessionFactory.GetCurrentSession());
 }
Пример #20
0
    public Task TestFileSave() {
      var response = new FileState {
        Name = "newBekti.png",
        Url = new Uri("https://www.parse.com/newBekti.png"),
        MimeType = "image/png"
      };
      var mockController = new Mock<IParseFileController>();
      mockController.Setup(obj => obj.SaveAsync(It.IsAny<FileState>(),
          It.IsAny<Stream>(),
          It.IsAny<string>(),
          It.IsAny<IProgress<ParseUploadProgressEventArgs>>(),
          It.IsAny<CancellationToken>())).Returns(Task.FromResult(response));
      var mockCurrentUserController = new Mock<IParseCurrentUserController>();
      ParseCorePlugins.Instance.FileController = mockController.Object;
      ParseCorePlugins.Instance.CurrentUserController = mockCurrentUserController.Object;

      ParseFile file = new ParseFile("bekti.jpeg", new MemoryStream(), "image/jpeg");
      Assert.AreEqual("bekti.jpeg", file.Name);
      Assert.AreEqual("image/jpeg", file.MimeType);
      Assert.True(file.IsDirty);

      return file.SaveAsync().ContinueWith(t => {
        Assert.False(t.IsFaulted);
        Assert.AreEqual("newBekti.png", file.Name);
        Assert.AreEqual("image/png", file.MimeType);
        Assert.AreEqual("https://www.parse.com/newBekti.png", file.Url.AbsoluteUri);
        Assert.False(file.IsDirty);
      });
    }
Пример #21
0
 public void Init()
 {
     connectionMock = new Mock<IConnectionChecker>();
     loginMock = new Mock<IAuthorizer>();
     converterMock = new Mock<IUrlConverter>();
     dataProviderMock = new Mock<IDatabaseProvider>();
 }
        protected void Arrange()
        {
            var random = new Random();
            _path = random.Next().ToString(CultureInfo.InvariantCulture);
            _handle = new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) };
            _fileAttributes = SftpFileAttributes.Empty;
            _bufferSize = (uint)random.Next(0, 1000);
            _readBufferSize = (uint)random.Next(0, 1000);
            _writeBufferSize = (uint)random.Next(0, 1000);

            _sftpSessionMock = new Mock<ISftpSession>(MockBehavior.Strict);

            var sequence = new MockSequence();
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestOpen(_path, Flags.Write | Flags.Truncate, true))
                .Returns(_handle);
            _sftpSessionMock.InSequence(sequence).Setup(p => p.RequestFStat(_handle)).Returns(_fileAttributes);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.CalculateOptimalReadLength(_bufferSize))
                .Returns(_readBufferSize);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.CalculateOptimalWriteLength(_bufferSize, _handle))
                .Returns(_writeBufferSize);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.IsOpen)
                .Returns(true);
            _sftpSessionMock.InSequence(sequence)
                .Setup(p => p.RequestClose(_handle));

            _sftpFileStream = new SftpFileStream(_sftpSessionMock.Object, _path, FileMode.Create, FileAccess.Write, (int)_bufferSize);
        }
        public void TestAddInterviewerToFieldworkOfficesAsync_WhenExecuted_CallsClientPostAsJsonAsyncWithCorrectArgs()
        {
            const string interviewerId = "interviewerId";
            const string fieldworkOfficeId = "Barcelona";

            var expectedUrl = string.Format(CultureInfo.InvariantCulture, "{0}interviewers/{1}/Offices",
                ServiceAddress,
                interviewerId);

            var mockedNfieldConnection = new Mock<INfieldConnectionClient>();
            var mockedHttpClient = CreateHttpClientMock(mockedNfieldConnection);

            mockedHttpClient
                .Setup(client => client.PostAsJsonAsync(It.IsAny<string>(), It.IsAny<InterviewerFieldworkOfficeModel>()))
                .Returns(CreateTask(HttpStatusCode.OK));

            var target = new NfieldInterviewersService();
            target.InitializeNfieldConnection(mockedNfieldConnection.Object);

            target.AddInterviewerToFieldworkOfficesAsync(interviewerId, fieldworkOfficeId);

            mockedHttpClient.Verify(
                h =>
                    h.PostAsJsonAsync(expectedUrl, It.Is<InterviewerFieldworkOfficeModel>(f => f.OfficeId == fieldworkOfficeId)),
                Times.Once());
        }
        private ExecuteMessage RunOutput(bool expectCorrectInput)
        {
            var esbMethod = new DeleteScheduledResource();
            var factory = new Mock<IServerSchedulerFactory>();
            var model = new Mock<IScheduledResourceModel>();
            var ws = new Mock<IWorkspace>();
            var trigger = new ScheduleTrigger(TaskState.Disabled,
                                              new Dev2DailyTrigger(new TaskServiceConvertorFactory(), new DailyTrigger(21)),
                                              new Dev2TaskService(new TaskServiceConvertorFactory()),
                                              new TaskServiceConvertorFactory());
            var res = new ScheduledResource("a", SchedulerStatus.Enabled, DateTime.Now, trigger, "dave");
            var security = new Mock<ISecurityWrapper>();
            esbMethod.SecurityWrapper = security.Object;

            Dictionary<string, StringBuilder> inp = new Dictionary<string, StringBuilder>();
            factory.Setup(
                a =>
                a.CreateModel(GlobalConstants.SchedulerFolderId, It.IsAny<ISecurityWrapper>())).Returns(model.Object);
            Dev2JsonSerializer serialiser = new Dev2JsonSerializer();
            if(expectCorrectInput)
            {

                model.Setup(a => a.DeleteSchedule(It.IsAny<ScheduledResource>())).Verifiable();
                inp.Add("Resource", serialiser.SerializeToBuilder(res));
            }

            esbMethod.SchedulerFactory = factory.Object;

            var output = esbMethod.Execute(inp, ws.Object);
            if(expectCorrectInput)
                model.Verify(a => a.DeleteSchedule(It.IsAny<ScheduledResource>()));
            return serialiser.Deserialize<ExecuteMessage>(output);

        }
Пример #25
0
        public static TestableChat GetTestableChat(string connectionId, StateChangeTracker clientState, ChatUser user, IDictionary<string, Cookie> cookies)
        {
            // setup things needed for chat
            var repository = new InMemoryRepository();
            var resourceProcessor = new Mock<IResourceProcessor>();
            var chatService = new Mock<IChatService>();
            var connection = new Mock<IConnection>();
            var settings = new Mock<IApplicationSettings>();
            var mockPipeline = new Mock<IHubPipelineInvoker>();

            // add user to repository
            repository.Add(user);

            // create testable chat
            var chat = new TestableChat(settings, resourceProcessor, chatService, repository, connection);
            var mockedConnectionObject = chat.MockedConnection.Object;

            chat.Clients = new HubConnectionContext(mockPipeline.Object, mockedConnectionObject, "Chat", connectionId, clientState);

            var prinicipal = new Mock<IPrincipal>();

            var request = new Mock<IRequest>();
            request.Setup(m => m.Cookies).Returns(cookies);
            request.Setup(m => m.User).Returns(prinicipal.Object);

            // setup context
            chat.Context = new HubCallerContext(request.Object, connectionId);

            return chat;
        }
Пример #26
0
        public void ShouldReturnDependenciesMarkedWithAttribute()
        {
            ITask dep = new Mock<ITask>().Object;
            var task = new ATask {A = dep};

            Assert.That(task.Dependencies.Select(d => d.Task), Is.EquivalentTo(new[] {dep}));
        }
 public void Initialise()
 {
     _blogRepo = new SimpleRepository<Data.Blog>(new InMemoryRepositoryDataSource<Data.Blog>(new List<Data.Blog> { new Data.Blog { Id = 1, AuthoritiveUrl = "http://blog.test.con" } }));
     _templateRepo =  new SimpleRepository<BlogTemplate>(new InMemoryRepositoryDataSource<BlogTemplate>());
     _mockHttpContext = new Mock<IHttpContextService>();
     _mockHttpContext.Setup(h => h.RequestUrl).Returns(new Uri("http://blog.test.con/blah"));
 }
        public void ListAll_PerformsCorrectRequest()
        {
            //Setup
            var request = new CategoriesStub("DevKey", "api.careerbuilder.com", "", "");

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

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

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

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

            //Assert
            List<Category> cats = request.WhereCountryCode(CountryCode.NL).ListAll();
            Assert.IsTrue(cats.Count == 0);
            restReq.VerifyAll();
            restClient.VerifyAll();
        }
Пример #29
0
        public SelectTests()
        {
            var html = @"

            <div>
            <span class=""center"">here</span>
            <a href=""http://google.com"">link</a>
            <div class=""dollar"">$6,566.00</div>
            <span class=""address"">4332 Forest Hill Blvd<br>West Palm Beach, FL 33406</span>
            <div id=""match-tests"">
            <li>6,566</li>
            <li>6</li>
            <li>8,975</li>
            <li>6,566,888</li>
            </div>
            <div id=""match-tests"">
            <li>10,566</li>
            <li>3</li>
            <li>1,975</li>
            <li>2,566,888</li>
            </div>
            </div>

            ";
            var httpRequest = new Mock<IHttpRequest>();
            httpRequest.Setup(x => x.Download()).Returns(System.Text.Encoding.UTF8.GetBytes(html));

            var requestFactory = new Mock<IHttpRequestFactory>();
            requestFactory.Setup(x => x.Create(It.IsAny<IHttpWire>())).Returns(httpRequest.Object);
            _requestFactory = requestFactory.Object;
        }
Пример #30
0
        private static IPackageService CreateService(
            Mock<IEntityRepository<PackageRegistration>> packageRegistrationRepository = null,
            Mock<IEntityRepository<Package>> packageRepository = null,
            Mock<IEntityRepository<PackageStatistics>> packageStatsRepo = null,
            Mock<IEntityRepository<PackageOwnerRequest>> packageOwnerRequestRepo = null,
            Mock<IIndexingService> indexingService = null,
            Action<Mock<PackageService>> setup = null)
        {
            packageRegistrationRepository = packageRegistrationRepository ?? new Mock<IEntityRepository<PackageRegistration>>();
            packageRepository = packageRepository ?? new Mock<IEntityRepository<Package>>();
            packageStatsRepo = packageStatsRepo ?? new Mock<IEntityRepository<PackageStatistics>>();
            packageOwnerRequestRepo = packageOwnerRequestRepo ?? new Mock<IEntityRepository<PackageOwnerRequest>>();
            indexingService = indexingService ?? new Mock<IIndexingService>();

            var packageService = new Mock<PackageService>(
                packageRegistrationRepository.Object,
                packageRepository.Object,
                packageStatsRepo.Object,
                packageOwnerRequestRepo.Object,
                indexingService.Object);

            packageService.CallBase = true;

            if (setup != null)
            {
                setup(packageService);
            }

            return packageService.Object;
        }