当前位置: 首页>>代码示例>>C#>>正文


C# Mock.Setup方法代码示例

本文整理汇总了C#中Mock.Setup方法的典型用法代码示例。如果您正苦于以下问题:C# Mock.Setup方法的具体用法?C# Mock.Setup怎么用?C# Mock.Setup使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Mock的用法示例。


在下文中一共展示了Mock.Setup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GetTestableChat

        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;
        }
开发者ID:ucdavis,项目名称:JabbR,代码行数:30,代码来源:ChatFacts.cs

示例2: ConnectControlViewModel_AddNewServer_ResourceRepositoryReturnExistingServers_False

 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);
 }
开发者ID:Robin--,项目名称:Warewolf,代码行数:30,代码来源:ConnectControlViewModelTests.cs

示例3: ExecuteAsync_calls_Commit_if_no_transaction

        public async Task ExecuteAsync_calls_Commit_if_no_transaction()
        {
            var mockModificationCommandBatch = new Mock<ModificationCommandBatch>();
            mockModificationCommandBatch.Setup(m => m.ModificationCommands.Count).Returns(1);

            var mockRelationalConnection = new Mock<IRelationalConnection>();
            var transactionMock = new Mock<IDbContextTransaction>();

            IDbContextTransaction currentTransaction = null;
            mockRelationalConnection.Setup(m => m.BeginTransaction()).Returns(() => currentTransaction = transactionMock.Object);
            mockRelationalConnection.Setup(m => m.CurrentTransaction).Returns(() => currentTransaction);

            var cancellationToken = new CancellationTokenSource().Token;

            var batchExecutor = new BatchExecutor();

            await batchExecutor.ExecuteAsync(new[] { mockModificationCommandBatch.Object }, mockRelationalConnection.Object, cancellationToken);

            mockRelationalConnection.Verify(rc => rc.OpenAsync(cancellationToken));
            mockRelationalConnection.Verify(rc => rc.Close());
            transactionMock.Verify(t => t.Commit());

            mockModificationCommandBatch.Verify(mcb => mcb.ExecuteAsync(
                It.IsAny<IRelationalConnection>(),
                cancellationToken));
        }
开发者ID:ChuYuzhi,项目名称:EntityFramework,代码行数:26,代码来源:BatchExecutorTest.cs

示例4: Home_Page_With_Custom_Action

        public void Home_Page_With_Custom_Action(string virtualUrl)
        {
            // Arrange
            var pathData = new PathData();
            var mapper = new Mock<IControllerMapper>();
            var container = new Mock<IContainer>();

            mapper.Setup(x => x.GetControllerName(typeof(DummyController))).Returns("Dummy");
            mapper.Setup(x => x.ControllerHasAction("Dummy", "myaction")).Returns(true);
            container.Setup(x => x.GetInstance<IDocumentSession>()).Returns(_store.OpenSession());

            mapper.Setup(m => m.ControllerHasAction("Content", "myaction")).Returns(true);

            // Act
            IPathData data;
            using (var session = _store.OpenSession()) {
                // create and store a new page model
                var pageModel = new DummyModel { Parent = null };
                session.Store(pageModel);
                session.SaveChanges();

                var resolver = new PathResolver(session, pathData, mapper.Object, container.Object);
                data = resolver.ResolvePath(new RouteData(), virtualUrl);
            }

            // Assert
            Assert.NotNull(data);
            Assert.AreEqual("myaction", data.Action);
            Assert.AreEqual("Dummy", data.Controller);
        }
开发者ID:stemyers,项目名称:BrickPile,代码行数:30,代码来源:PathResolverTests.cs

示例5: RuntimeControllerReturnsNodeVersions

        public void RuntimeControllerReturnsNodeVersions()
        {
            // Arrange
            var nodeDir = new Mock<DirectoryInfoBase>();
            nodeDir.Setup(d => d.Exists).Returns(true);
            nodeDir.Setup(d => d.GetDirectories()).Returns(new[] { 
                CreateDirectory("0.8.19", CreateFile("npm.txt", "1.2.8")), 
                CreateDirectory("0.10.5", CreateFile("npm.txt", "1.3.11")), 
                CreateDirectory("0.10.18"), 
                CreateDirectory("node_modules"), 
                CreateDirectory("docs") 
            });
            var directoryInfo = new Mock<IDirectoryInfoFactory>();
            directoryInfo.Setup(d => d.FromDirectoryName(_nodeDir)).Returns(nodeDir.Object);
            var fileSystem = new Mock<IFileSystem>();
            fileSystem.Setup(f => f.DirectoryInfo).Returns(directoryInfo.Object);
            FileSystemHelpers.Instance = fileSystem.Object;
            var controller = new RuntimeController(Mock.Of<ITracer>());

            // Act
            var nodeVersions = controller.GetRuntimeVersions().NodeVersions.ToList();

            // Assert
            Assert.Equal(new[] { "0.8.19", "0.10.5", "0.10.18" }, nodeVersions.Select(v => v["version"]));
            Assert.Equal(new[] { "1.2.8", "1.3.11", null }, nodeVersions.Select(v => v["npm"]));
        }
开发者ID:40a,项目名称:kudu,代码行数:26,代码来源:RuntimeControllerFacts.cs

示例6: Insert_Poco

        public void Insert_Poco()
        {
            //Just a few props as it is just to test that it runs
            var user = TestDataHelper.GetUserList().First();
            var newUser = new InsertUser
            {
                Id = Guid.NewGuid(),
                Name = user.Name
            };

            var sessionMock = new Mock<ISession>(MockBehavior.Strict);
            sessionMock
                .Setup(s => s.ExecuteAsync(It.IsAny<BoundStatement>()))
                .Returns(TestHelper.DelayedTask(new RowSet()))
                .Verifiable();
            sessionMock
                .Setup(s => s.PrepareAsync(It.IsAny<string>()))
                .Returns<string>(cql => TaskHelper.ToTask(GetPrepared(cql)))
                .Verifiable();
            var mappingClient = GetMappingClient(sessionMock);
            //Execute
            mappingClient.Insert(newUser);
            sessionMock.Verify(s => s.ExecuteAsync(It.Is<BoundStatement>(stmt =>
                stmt.QueryValues.Length == TestHelper.ToDictionary(newUser).Count &&
                stmt.PreparedStatement.Cql.StartsWith("INSERT INTO users (")
                )), Times.Exactly(1));
            sessionMock.Verify();
        }
开发者ID:Virus-X,项目名称:csharp-driver,代码行数:28,代码来源:InsertTests.cs

示例7: FoodItemAddedToChildrenWhenAddedToRepository

        public void FoodItemAddedToChildrenWhenAddedToRepository()
        {
            var configurationMock = new Mock<IConfiguration>();
             configurationMock.Setup( x => x.DataSource ).Returns( DataSourceType.XMLFile );
             configurationMock.Setup( x => x.FileName ).Returns( FullTestData.DataFileName );

             FullTestData.Reset();
             DataRepository dataRepository = new DataRepository( configurationMock.Object );

             FoodItemNodeViewModel foodItemNodeViewModel = new FoodItemNodeViewModel( dataRepository, null );

             Int32 originalChildCount = foodItemNodeViewModel.Children.Count;

             FoodItem newFoodItem = new FoodItem( Guid.NewGuid(), "New Food Item", "Some Description", 92 );
             newFoodItem.FoodGroupsPerServing.Add( new Serving<FoodGroup>( dataRepository.GetAllFoodGroups()[0], 1 ) );
             dataRepository.SaveItem( newFoodItem );
             Assert.AreEqual( originalChildCount + 1, foodItemNodeViewModel.Children.Count );

             foreach (ClickableTreeNodeViewModel node in foodItemNodeViewModel.Children)
             {
            FoodItem foodItem = dataRepository.GetFoodItem( (Guid)node.Parameter );
            Assert.IsNotNull( foodItem );
            Assert.AreEqual( foodItem.Name, node.Name );
             }
        }
开发者ID:nagyist,项目名称:HealthTracker-1,代码行数:25,代码来源:FoodItemNodeViewModelTest.cs

示例8: WillDelegateContentNotInMyDirectoryFriendHandlers

        public void WillDelegateContentNotInMyDirectoryFriendHandlers()
        {
            var module = new RequestReduceModule();
            var handler = new DefaultHttpHandler();
            var config = new Mock<IRRConfiguration>();
            config.Setup(x => x.SpriteVirtualPath).Returns("/RRContent");
            var context = new Mock<HttpContextBase>();
            context.Setup(x => x.Request.RawUrl).Returns("/content/someresource.less");
            context.Setup(x => x.Request.Url).Returns(new Uri("http://host/content/someresource.less"));
            context.Setup(x => x.Request.Headers).Returns(new NameValueCollection());
            context.Setup(x => x.Server).Returns(new Mock<HttpServerUtilityBase>().Object);
            context.Setup(x => x.Items).Returns(new Hashtable());
            RRContainer.Current = new Container(x =>
            {
                x.For<IRRConfiguration>().Use(config.Object);
                x.For<IUriBuilder>().Use<UriBuilder>();
            });
            Registry.HandlerMaps.Add(x => x.AbsolutePath.EndsWith(".less") ? handler : null);
            Registry.HandlerMaps.Add(x => x.AbsolutePath.EndsWith(".les") ? new DefaultHttpHandler() : null);

            module.HandleRRContent(context.Object);

            //context.Verify(x => x.RemapHandler(handler), Times.Once());
            Assert.Equal(handler, context.Object.Items["remapped handler"]);
            RRContainer.Current = null;
            Registry.HandlerMaps.Clear();
        }
开发者ID:bizzarry,项目名称:RequestReduce,代码行数:27,代码来源:RequestReduceModuleFacts.cs

示例9: Styles_client_retrieves_last_known_good_content_from_local_cache_if_service_throws_exception

        public void Styles_client_retrieves_last_known_good_content_from_local_cache_if_service_throws_exception()
        {
            // Arrange
            var service = new Mock<IStylesService>();

            service.Setup(x => x.Get(ContentTypes.Intranet_FatFooter)).Throws(new Exception("Unit test exception"));
            var cache = new Mock<ILocalCache<List<ContentStyle>>>();
            cache.Setup(x => x.WriteToCache(ContentTypes.Intranet_FatFooter, It.IsAny<List<ContentStyle>>(), It.IsAny<DateTime>()));
            var styles = new List<ContentStyle>
            {
                new ContentStyle
                {
                    Url = new Uri("http://styles.com/1.css")
                }
            };
            cache.Setup(x => x.ReadFromCache(ContentTypes.Intranet_FatFooter)).Returns(styles);
            var client = new StylesClient(service.Object, cache.Object);

            // Act
            client.Get(ContentTypes.Intranet_FatFooter);

            // Assert
            service.Verify(x => x.Get(ContentTypes.Intranet_FatFooter), Times.Once);
            cache.Verify(x => x.ReadFromCache(ContentTypes.Intranet_FatFooter), Times.Once);
            cache.Verify(x => x.WriteToCache(ContentTypes.Intranet_FatFooter, It.IsAny<List<ContentStyle>>(), It.IsAny<DateTime>()), Times.Never);
        }
开发者ID:ukp-webdev,项目名称:veneer-client,代码行数:26,代码来源:StylesClientTests.cs

示例10: BrokerRouterProxy

        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
                });
        }
开发者ID:pooyasoleimany,项目名称:KafkaNetClient,代码行数:27,代码来源:BrokerRouterProxy.cs

示例11: json_collection_with_default_culture_test

        public void json_collection_with_default_culture_test()
        {
            // Arrange
            var req = new Mock<HttpRequest>();
            req.Setup(x => x.Headers)
                .Returns(new HeaderDictionary(new Dictionary<string, StringValues> { }));
            req.Setup(x => x.Cookies)
                .Returns(new RequestCookiesCollection());
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(x => x.Request)
                .Returns(req.Object);
            var accessor = new Mock<IHttpContextAccessor>();
            accessor.Setup(x => x.HttpContext)
                .Returns(httpContext.Object);

            var collection = new ServiceCollection();
            collection.AddJsonLocalization()
                .AddCookieCulture()
                .AddInstance(accessor.Object)
                .AddInstance(CallContextServiceLocator.Locator.ServiceProvider.GetRequiredService<IApplicationEnvironment>());

            var service = collection.BuildServiceProvider();

            // Act
            var SR = service.GetService<ILocalizationStringCollection>();
            var actual_1 = SR["Hello world."];
            var actual_2 = SR["My name is {0}.", "Yuuko"];

            // Assert
            Assert.Equal("你好,世界。", actual_1);
            Assert.Equal("我的名字是Yuuko", actual_2);
        }
开发者ID:CodeComb,项目名称:Localization,代码行数:32,代码来源:JsonCollectionTests.cs

示例12: StatisticsHomePage_ValidateReportStructureAndAvailability

        public async void StatisticsHomePage_ValidateReportStructureAndAvailability()
        {
            var fakePackageReport = "[{\"PackageId\":\"A\",\"Downloads\":1},{\"PackageId\":\"B\",\"Downloads\":2}]";
            var fakePackageVersionReport = "[{\"PackageId\":\"A\",\"PackageVersion\":\"1.0\",\"Downloads\":3},{\"PackageId\":\"A\",\"PackageVersion\":\"1.1\",\"Downloads\":4},{\"PackageId\":\"B\",\"PackageVersion\":\"1.0\",\"Downloads\":5}]";

            var fakeReportService = new Mock<IReportService>();

            fakeReportService.Setup(x => x.Load("RecentPopularity.json")).Returns(Task.FromResult(fakePackageReport));
            fakeReportService.Setup(x => x.Load("RecentPopularityDetail.json")).Returns(Task.FromResult(fakePackageVersionReport));

            var controller = new StatisticsController(new JsonStatisticsService(fakeReportService.Object));

            var model = (StatisticsPackagesViewModel)((ViewResult) await controller.Index()).Model;

            int sum = 0;

            if (model.IsDownloadPackageAvailable)
            {
                foreach (var item in model.DownloadPackagesSummary)
                {
                    sum += item.Downloads;
                }
            }

            if (model.IsDownloadPackageDetailAvailable)
            {
                foreach (var item in model.DownloadPackageVersionsSummary)
                {
                    sum += item.Downloads;
                }
            }

            Assert.Equal<int>(15, sum);
        }
开发者ID:ChrisMissal,项目名称:NuGetGallery,代码行数:34,代码来源:StatisticsControllerFacts.cs

示例13: TestUseCombinedSkinsSchemaWhenNoDefaultTemplate

		public void TestUseCombinedSkinsSchemaWhenNoDefaultTemplate()
		{
			var templateInfo = new StringTemplateInfo("test", "");
			var templateInfo2 = new StringTemplateInfo("test2", "");
			var schema1 = new JSchema();
            var schema2 = new JSchema();

			var templateSchemaProvider = new Mock<ISchemaProvider>();
			templateSchemaProvider.Setup(f => f.GetSchemaFromTemplateAsync(templateInfo)).Returns(Task.FromResult(schema1));
			templateSchemaProvider.Setup(f => f.GetSchemaFromTemplateAsync(templateInfo2)).Returns(Task.FromResult(schema2));

			var combiner = new Mock<SchemaCombiner>();
			combiner.Setup(c =>
                c.Apply(It.Is<JSchema>(s => s == schema1), It.Is<JSchema>(s => s == schema2), It.IsAny<SchemaComparisionReport>(), It.IsAny<string>()))
                .Returns(new JSchema());

			var moduleDefintion = new ModuleDefinition("testmod", null, new Dictionary<string, TemplateInfo>
            {
				{"skin1", templateInfo},
                {"skin2", templateInfo2}
            });

			var underTest = new DefaultModuleSchemaProvider(combiner.Object, templateSchemaProvider.Object);

			var result = underTest.GetSchemaFromModuleAsync(moduleDefintion);

			Assert.IsNotNull(result);

			combiner.Verify();
		}
开发者ID:namics,项目名称:TerrificNet,代码行数:30,代码来源:DefaultModuleSchemaProviderTest.cs

示例14: Setup

        public void Setup()
        {
            _genericEditSummaryViewModel = new EditSummaryViewModel()
            {
                CompanyId = 123L,
                RiskAssessmentId = 789L,
                DateOfAssessment = DateTime.Now,
                HazardousSubstanceId = 456L,
                Title = "title",
                Reference = "reference",
                RiskAssessorId = 567L
            };
            _viewModelFactory = new Mock<IEditHazardousSubstanceRiskAssessmentSummaryViewModelFactory>();
            _viewModelFactory
                .Setup(x => x.WithRiskAssessmentId(It.IsAny<long>()))
                .Returns(_viewModelFactory.Object);
            _viewModelFactory
                .Setup(x => x.WithCompanyId(It.IsAny<long>()))
                .Returns(_viewModelFactory.Object);
            _viewModelFactory
                .Setup(x => x.GetViewModel())
                .Returns(new EditSummaryViewModel());

            _riskAssessmentService = new Mock<IHazardousSubstanceRiskAssessmentService>();
            _riskAssessmentService.Setup(x => x.UpdateRiskAssessmentSummary(It.IsAny<SaveHazardousSubstanceRiskAssessmentRequest>()));

            target = GetTarget();
        }
开发者ID:mnasif786,项目名称:Business-Safe,代码行数:28,代码来源:SaveAndNextTests.cs

示例15: Test_Authenticate

        public void Test_Authenticate()
        {
            //arrange
            var clusterMock = new Mock<ICluster>();
            clusterMock.Setup(x => x.OpenBucket(It.IsAny<string>())).Returns(new Mock<IBucket>().Object);
            clusterMock.Setup(x => x.Authenticate(It.IsAny<IClusterCredentials>()));
            var cluster = clusterMock.Object;

            var credentials = new ClusterCredentials
            {
                ClusterUsername = "Administrator",
                ClusterPassword = "",
                BucketCredentials = new Dictionary<string, string>
                {
                    {"default", "" },
                    {"authenticated", "secret" },
                    {"memcached", "" },
                    {"travel-sample", "wayward1" }
                }
            };

            //act
            cluster.Authenticate(credentials);
            var bucket = cluster.OpenBucket("authenticated");

            //assert
            Assert.IsNotNull(bucket);
        }
开发者ID:brantburnett,项目名称:couchbase-net-client,代码行数:28,代码来源:AuthenticatorTests.cs


注:本文中的Mock.Setup方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。