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


C# Mock.SetupSequence方法代码示例

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


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

示例1: InitializeGetChildItemsAsyncWithFilter

        public Mock<IAsyncCloudGateway> InitializeGetChildItemsAsyncWithFilter(RootName rootName, string path, string filter, params IEnumerable<FileSystemInfoContract>[] pathChildItems)
        {
            var gatewayMock = new Mock<IAsyncCloudGateway>(MockBehavior.Strict);
            gatewayMock.SetupSequence(g => g.GetRootAsync(rootName, FileSystemFixture.ApiKey))
                .ReturnsAsync(FileSystemFixture.Root)
                .ThrowsAsync(new InvalidOperationException("Redundant call to GetRoot()"));
            gatewayMock.SetupSequence(g => g.GetDriveAsync(rootName, FileSystemFixture.ApiKey))
                .ReturnsAsync(FileSystemFixture.Drive)
                .Throws(new InvalidOperationException("Redundant call to GetDrive()"));

            if (path != null) {
                path = path + Path.DirectorySeparatorChar;
                for (int i = 0, j = 0; i >= 0; i = path.IndexOf(Path.DirectorySeparatorChar, Math.Min(path.Length, i + 2)), ++j) {
                    var currentPath = new DirectoryId(path.Substring(0, Math.Max(1, i)));

                    bool applyFilter = j == pathChildItems.Length - 1;
                    var effectiveFilter = applyFilter && filter != null ? new Regex("^" + filter.Replace("*", ".*") + "$") : null;
                    gatewayMock.SetupSequence(g => g.GetChildItemAsync(rootName, currentPath))
                        .ReturnsAsync(applyFilter ? pathChildItems[j].Where(f => effectiveFilter == null || effectiveFilter.IsMatch(f.Name)) : pathChildItems[j])
                        .ThrowsAsync(new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "Redundant access to {0}", currentPath)));
                }
            }

            return gatewayMock;
        }
开发者ID:viciousviper,项目名称:PowerShellCloudProvider,代码行数:25,代码来源:MockingFixture.cs

示例2: setUpBeforeEachTest

        public void setUpBeforeEachTest()
        {
            litle = new litleRequest();

            mockXmlReader = new Mock<XmlReader>();
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadToFollowing(It.IsAny<String>())).Returns(true).Returns(true).Returns(false);
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadState).Returns(ReadState.Initial).Returns(ReadState.Interactive).Returns(ReadState.Closed);
        }
开发者ID:hriyer,项目名称:litle-sdk-for-dotNet,代码行数:8,代码来源:TestBatch.cs

示例3: GetWeatherAsync_2ClientsWithOneClientWrong

        public async void GetWeatherAsync_2ClientsWithOneClientWrong()
        {
            var mockHttpClient = new Mock<IHttpClient>();

            //Arrange 
            mockHttpClient.SetupSequence(x => x.GetStringAsync(It.IsAny<string>()))
            //BBC
            .Returns(Task.Run<HttpClientResponse>(() => DataTest.HttpClientResponse["BBCWeatherOK"]))
            //AccuWeather
            .Returns(Task.Run<HttpClientResponse>(() => DataTest.HttpClientResponse["Wrong"]));


            var moclHttpClientFactory = new Mock<IHttpClientFactory>();
            moclHttpClientFactory.Setup(x => x.GetHttpClient<HttpClientWrapper>()).Returns(mockHttpClient.Object);

            _container.RegisterInstance<IHttpClientFactory>(moclHttpClientFactory.Object);

            var manager = _container.Resolve<ApiWeatherManager>();

            //Act
            var result = await manager.GetWeatherAsync("anylocation", Api.Weather.TemperatureUnits.Farenheits, Api.Weather.WindUnits.MPHs);

            //Assert
            result.WindUnit.Should().Be(WindUnits.MPHs);
            result.TemperatureUnit.Should().Be(TemperatureUnits.Farenheits);
            result.Wind.Should().Be(0.62f);
            result.Temperature.Should().Be(77);
        }
开发者ID:zalayeto,项目名称:WeatherTest,代码行数:28,代码来源:ApiWeatherManagerTest.cs

示例4: Main_WithTwoValidCommands_ExitsProgramWhenEmptyStringIsEntered

        public void Main_WithTwoValidCommands_ExitsProgramWhenEmptyStringIsEntered()
        {
            // Arrange
            Mock<IStringCalculator> mockCalculator = new Mock<IStringCalculator>();
            Mock<IConsole> mockConsole = new Mock<IConsole>();
            mockCalculator.Setup(c => c.Add("1,2,3")).Returns(6);
            mockCalculator.Setup(c => c.Add("3")).Returns(3);
            mockCalculator.Setup(c => c.Add("5")).Returns(5);

            mockConsole.SetupSequence(c => c.ReadLine())
                .Returns("3")
                .Returns("5")
                .Returns("");

            StringCalculatorConsole stringCalculatorConsole = CreateCalcConsole(mockCalculator, mockConsole);

            // Act
            stringCalculatorConsole.Main(new string[] { "scalc '1,2,3'" });

            // Assert
            mockConsole.Verify(c => c.WriteLine("The result is 6"));
            mockConsole.Verify(c => c.WriteLine("another input please"), Times.Exactly(3));
            mockConsole.Verify(c => c.WriteLine("The result is 3"));
            mockConsole.Verify(c => c.WriteLine("The result is 5"));
            mockConsole.Verify(c => c.ReadLine(), Times.Exactly(3));
        }
开发者ID:neelanshu,项目名称:StringCalculator,代码行数:26,代码来源:CalculatorConsoleTests.cs

示例5: WriteFileAsync_WritesResponse_InChunksOfFourKilobytes

        public async Task WriteFileAsync_WritesResponse_InChunksOfFourKilobytes()
        {
            // Arrange
            var mockReadStream = new Mock<Stream>();
            mockReadStream.SetupSequence(s => s.ReadAsync(It.IsAny<byte[]>(), 0, 0x1000, CancellationToken.None))
                .Returns(Task.FromResult(0x1000))
                .Returns(Task.FromResult(0x500))
                .Returns(Task.FromResult(0));

            var mockBodyStream = new Mock<Stream>();
            mockBodyStream
                .Setup(s => s.WriteAsync(It.IsAny<byte[]>(), 0, 0x1000, CancellationToken.None))
                .Returns(Task.FromResult(0));

            mockBodyStream
                .Setup(s => s.WriteAsync(It.IsAny<byte[]>(), 0, 0x500, CancellationToken.None))
                .Returns(Task.FromResult(0));

            var result = new FileStreamResult(mockReadStream.Object, "text/plain");

            var httpContext = GetHttpContext();
            httpContext.Response.Body = mockBodyStream.Object;

            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            mockReadStream.Verify();
            mockBodyStream.Verify();
        }
开发者ID:xuchrist,项目名称:Mvc,代码行数:32,代码来源:FileStreamResultTest.cs

示例6: SerializeError_serializes_httperror

        public void SerializeError_serializes_httperror()
        {
            using (var stream = new MemoryStream())
            {
                var textWriter = new StreamWriter(stream);
                var writer = new JsonTextWriter(textWriter);

                var mockInnerException = new Mock<Exception>(MockBehavior.Strict);
                mockInnerException.Setup(m => m.Message).Returns("Inner exception message");
                mockInnerException.Setup(m => m.StackTrace).Returns("Inner stack trace");

                var outerException = new Exception("Outer exception message", mockInnerException.Object);

                var error = new HttpError(outerException, true)
                {
                    StackTrace = "Outer stack trace"
                };
                var jsonSerializer = new JsonSerializer();

                var mockIdProvider = new Mock<IErrorIdProvider>(MockBehavior.Strict);
                mockIdProvider.SetupSequence(p => p.GenerateId(It.IsAny<HttpError>())).Returns("OUTER-ID").Returns("INNER-ID");

                var serializer = new ErrorSerializer(mockIdProvider.Object);
                serializer.SerializeError(error, stream, writer, jsonSerializer);

                writer.Flush();

                var expectedJson = File.ReadAllText("ErrorSerializerTest.json");
                var minifiedExpectedJson = JsonHelpers.MinifyJson(expectedJson);
                var output = System.Text.Encoding.ASCII.GetString(stream.ToArray());
                output.Should().Be(minifiedExpectedJson);
            }
        }
开发者ID:Eclarian,项目名称:JSONAPI.NET,代码行数:33,代码来源:ErrorSerializerTests.cs

示例7: DisposeDisposesAllEngines

        public void DisposeDisposesAllEngines()
        {
            var engines = new[]
            {
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
                new Mock<IJsEngine>(),
            };
            var factory = new Mock<IEngineFactoryForMock>();
            factory.SetupSequence(x => x.EngineFactory())
                .Returns(engines[0].Object)
                .Returns(engines[1].Object)
                .Returns(engines[2].Object)
                .Returns(engines[3].Object);
            var config = new JsPoolConfig
            {
                StartEngines = 3,
                EngineFactory = factory.Object.EngineFactory
            };

            var pool = new JsPool(config);
            pool.Dispose();

            foreach (var engine in engines)
            {
                engine.Verify(x => x.Dispose());
            }
        }
开发者ID:RichardD012,项目名称:JSPool,代码行数:29,代码来源:JsPoolTests.cs

示例8: IntegrationTestProcessBatch

        public void IntegrationTestProcessBatch()
        {
            var orders = new List<IDummyOrderObject>();
            for (var i = 0; i < 6; i++)
            {
                var order = new Mock<IDummyOrderObject>();
                order.Setup(s => s.OrderNumber).Returns(i.ToString(CultureInfo.InvariantCulture));
                orders.Add(order.Object);
            }

            var repo = new Mock<IFraudRepository>();
            var mockRuleFailing = RuleGenerators.FetchMockedRule(true);
            var mockRulePassing = RuleGenerators.FetchMockedRule(false);
            repo
                .SetupSequence(m => m.FetchAllRules())
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object })
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object })
                .Returns(new List<IFraudRule> { mockRuleFailing.Object })
                .Returns(new List<IFraudRule> { mockRulePassing.Object });

            var bulkProcessor = new FraudCheckerBulkProcessor(repo.Object);
            var report = bulkProcessor.ProcessBatch(orders);

            Assert.AreEqual(6, report.Count);
            Assert.IsFalse(report["0"].OverallResult);
            Assert.IsTrue(report["1"].OverallResult);
            Assert.IsFalse(report["2"].OverallResult);
            Assert.IsTrue(report["3"].OverallResult);
            Assert.IsFalse(report["4"].OverallResult);
            Assert.IsTrue(report["5"].OverallResult);
        }
开发者ID:Chane,项目名称:PipelinePlay,代码行数:33,代码来源:FraudCheckerBulkProcessorTests.cs

示例9: SwagOMeterViewModelShouldAwardSwagAndCanSwagSetToFalseWhenSwagAndAttendeesAreAllUsedUpAfterAward

        public void SwagOMeterViewModelShouldAwardSwagAndCanSwagSetToFalseWhenSwagAndAttendeesAreAllUsedUpAfterAward()
        {
            // Arrange
            var mockAttendee = new Mock<IAttendee>();
            mockAttendee.SetupGet(a => a.Name).Returns("Bob");

            var mockSwag = new Mock<ISwag>();
            mockSwag.SetupGet(s => s.Company).Returns("Company");
            mockSwag.SetupGet(s => s.Thing).Returns("Thing");

            var stubAttendeeSource = new Mock<IAttendeeSource>();

            var stubSwagSource = new Mock<ISwagSource>();

            var stubWinnersSource = new Mock<IWinnersSource>();

            var stubSwagOMeterEngine = new Mock<ISwagOMeterAwardEngine>();
            stubSwagOMeterEngine.Setup(e => e.CheckCanSwag()).Returns(true);
            stubSwagOMeterEngine.SetupSequence(e => e.CanSwag).Returns(true).Returns(false);
            stubSwagOMeterEngine.SetupGet(e => e.AwardedSwag).Returns(mockSwag.Object);
            stubSwagOMeterEngine.SetupGet(e => e.WinningAttendee).Returns(mockAttendee.Object);

            // Act
            var viewModel = new SwagOMeterViewModel(stubAttendeeSource.Object, stubSwagSource.Object, stubWinnersSource.Object, stubSwagOMeterEngine.Object);
            viewModel.ViewReady();
            viewModel.AwardSwagCommand.Execute(null);

            // Assert
            StringAssert.Matches(viewModel.WinningAttendee, new Regex("Bob"));
            StringAssert.Matches(viewModel.WonSwag, new Regex("Company Thing"));
            Assert.IsFalse(viewModel.CanSwag);
        }
开发者ID:imaji,项目名称:SwagOMeter,代码行数:32,代码来源:SwagOMeterViewModelTests.cs

示例10: GetEngineReturnsAllAvailableEngines

		public void GetEngineReturnsAllAvailableEngines()
		{
			var engines = new[]
			{
				new Mock<IJsEngine>().Object,
				new Mock<IJsEngine>().Object,
				new Mock<IJsEngine>().Object,
			};
			var factory = new Mock<IEngineFactoryForMock>();
			factory.SetupSequence(x => x.EngineFactory())
				// Initial call to factory is to determine engine type, we don't care
				// about that here.
				.Returns(new Mock<IJsEngine>().Object)
				.Returns(engines[0])
				.Returns(engines[1])
				.Returns(engines[2]);
			var config = new JsPoolConfig
			{
				StartEngines = 3,
				EngineFactory = factory.Object.EngineFactory
			};

			var pool = new JsPool(config);
			var resultEngines = new[]
			{
				pool.GetEngine(),
				pool.GetEngine(),
				pool.GetEngine(),
			};

			CollectionAssert.AreEquivalent(engines, resultEngines);
		}
开发者ID:modulexcite,项目名称:JSPool,代码行数:32,代码来源:JsPoolTests.cs

示例11: ThenIfOneResourceFailsToUploadThenAllAreReloaded

        public void ThenIfOneResourceFailsToUploadThenAllAreReloaded()
        {
            // Arrange: unsuccessful resource upload followed by two successful uploads
            var ckanApi = new Mock<ICkanApi>(MockBehavior.Strict);
            ckanApi.Setup(x => x.CreateResource(resource1)).Returns(resource1);
            ckanApi.SetupSequence(x => x.CreateResource(resource2))
                .Throws<CkanTimeoutException>()
                .Throws<CkanInternalServerException>()
                .Returns(resource2);

            // Arrange: package update after failed resource upload
            package.Resources.Add(resource1);
            ckanApi.Setup(x => x.GetPackage(packageId)).Returns(package);
            ckanApi.Setup(x => x.UpdatePackage(package)).Returns(package);

            // Act: upload resources
            var resources = UploadResources(ckanApi);

            // Assert: expected number of resources
            Assert.AreEqual(2, resources.Count);

            // Assert: package resources have been cleared
            Assert.AreEqual(0, package.Resources.Count);
            ckanApi.VerifyAll();
        }
开发者ID:PublicHealthEngland,项目名称:fingertips-open,代码行数:25,代码来源:CkanResourceUploaderTest.cs

示例12: GetControllersMetaData_LocalControllers_GetWithoutIgnoredAndSortedCorrectly

		public void GetControllersMetaData_LocalControllers_GetWithoutIgnoredAndSortedCorrectly()
		{
			// Assign

			SimplifyWebTypesFinder.ExcludedAssembliesPrefixes.Remove("Simplify");
			SimplifyWebTypesFinder.ExcludedAssembliesPrefixes.Add("DynamicProxyGenAssembly2");
			SimplifyWebTypesFinder.CleanLoadedTypesAndAssembliesInfo();

			var factory = new Mock<IControllerMetaDataFactory>();
			var store = new ControllersMetaStore(factory.Object);

			factory.SetupSequence(x => x.CreateControllerMetaData(It.IsAny<Type>()))
				.Returns(new ControllerMetaData(typeof(TestController1), new ControllerExecParameters(null, 2)))
				.Returns(new ControllerMetaData(typeof(TestController2), new ControllerExecParameters(null, 1)))
				.Returns(new ControllerMetaData(typeof(TestController4)))
				.Returns(new ControllerMetaData(typeof(TestController5)));

			// Act
			var metaData = store.ControllersMetaData;

			Assert.AreEqual(4, metaData.Count);
			Assert.AreEqual("TestController4", metaData[0].ControllerType.Name);
			Assert.AreEqual("TestController5", metaData[1].ControllerType.Name);
			Assert.AreEqual("TestController2", metaData[2].ControllerType.Name);
			Assert.AreEqual("TestController1", metaData[3].ControllerType.Name);

			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController1))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController2))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController4))));
			factory.Verify(x => x.CreateControllerMetaData(It.Is<Type>(t => t == typeof(TestController5))));
		}
开发者ID:i4004,项目名称:Simplify.Web,代码行数:31,代码来源:ControllersMetaStoreTests.cs

示例13: setUpBeforeEachTest

        public void setUpBeforeEachTest()
        {
            _mockConfig = new Dictionary<string, string>();
            _mockConfig["url"] = "https://www.mockurl.com";
            _mockConfig["reportGroup"] = "Mock Report Group";
            _mockConfig["username"] = "mockUser";
            _mockConfig["printxml"] = "false";
            _mockConfig["timeout"] = "35";
            _mockConfig["proxyHost"] = "www.mockproxy.com";
            _mockConfig["merchantId"] = "MOCKID";
            _mockConfig["password"] = "mockPassword";
            _mockConfig["proxyPort"] = "3000";
            _mockConfig["sftpUrl"] = "www.mockftp.com";
            _mockConfig["sftpUsername"] = "mockFtpUser";
            _mockConfig["sftpPassword"] = "mockFtpPassword";
            _mockConfig["knownHostsFile"] = "C:\\MockKnownHostsFile";
            _mockConfig["onlineBatchUrl"] = "www.mockbatch.com";
            _mockConfig["onlineBatchPort"] = "4000";
            _mockConfig["requestDirectory"] = "C:\\MockRequests";
            _mockConfig["responseDirectory"] = "C:\\MockResponses";

            _mockCache.Setup(x => x[_mockConfig["responseDirectory"] + "\\Responses\\" + mockFileName])
                .Returns(new StringBuilder());
            litle = new litleRequest(_mockCache.Object, _mockConfig);

            mockXmlReader = new Mock<XmlReader>();
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadToFollowing(It.IsAny<string>()))
                .Returns(true)
                .Returns(true)
                .Returns(false);
            mockXmlReader.SetupSequence(XmlReader => XmlReader.ReadState)
                .Returns(ReadState.Initial)
                .Returns(ReadState.Interactive)
                .Returns(ReadState.Closed);
        }
开发者ID:Coverdell,项目名称:litle-sdk-for-dotNet,代码行数:35,代码来源:TestBatch.cs

示例14: CallAsync_MethodWithReturnValue

        public async Task CallAsync_MethodWithReturnValue()
        {
            var mockService = new Mock<ITestService>();
            mockService
                .SetupSequence(m => m.TestMethod("good"))
                .Returns("BAD")
                .Returns("OK");

            mockService.Setup(m => m.TestMethod("second", "two")).Returns("2");

            var serviceHost = InProcTestFactory.CreateHost<ITestService>(new TestServiceImpl(mockService));

            var proxy = WcfClientProxy.CreateAsyncProxy<ITestService>(c =>
            {
                c.MaximumRetries(1);
                c.SetEndpoint(serviceHost.Binding, serviceHost.EndpointAddress);
                c.RetryOnResponse<string>(s => s == "BAD");
            });

            Console.WriteLine("Caller thread: " + Thread.CurrentThread.ManagedThreadId);

            string result = await proxy.CallAsync(m => m.TestMethod("good"));
            string result2 = await proxy.CallAsync(m => m.TestMethod("second", "two"));

            Console.WriteLine("Continuation thread: " + Thread.CurrentThread.ManagedThreadId);

            Assert.That(result, Is.EqualTo("OK"));
            Assert.That(result2, Is.EqualTo("2"));
        }
开发者ID:yonglehou,项目名称:WcfClientProxyGenerator,代码行数:29,代码来源:AsyncTests.cs

示例15: SetUp

        public void SetUp()
        {
            _archetype = ContentHelpers.Archetype;

            var content = ContentHelpers.FakeContent(123, "Fake Node 1", properties: new Collection<IPublishedProperty>
            {
                new FakePublishedProperty("myArchetypeProperty", _archetype, true)
            });

            _content = new FakeModel(content);
            _propertyDescriptor = TypeDescriptor.GetProperties(_content)["TextString"];

            _context = new FakeDittoValueResolverContext(_content, _propertyDescriptor);

            var mockedPropertyService = new Mock<PropertyValueService>();

            mockedPropertyService.SetupSequence(
                i =>
                    i.Set(It.IsAny<IPublishedContent>(), It.IsAny<CultureInfo>(), It.IsAny<PropertyInfo>(),
                        It.IsAny<object>(), It.IsAny<object>(), It.IsAny<DittoValueResolverContext>()))
                        .Returns(new HtmlString("<p>This is the <strong>summary</strong> text.</p>"))
                        .Returns("Ready to Enroll?")
                        .Returns("{}");

            _sut = new ArchetypeBindingService(mockedPropertyService.Object, new DittoAliasLocator());
        }
开发者ID:Nicholas-Westby,项目名称:Ditto.Resolvers,代码行数:26,代码来源:ArchetypeBindingServiceTests.cs


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