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


C# Mock.Expect方法代码示例

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


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

示例1: Setup

        public void Setup() {
            route = new Mock<RouteBase>();
            route.Expect(r => r.GetVirtualPath(It.IsAny<RequestContext>(), It.IsAny<RouteValueDictionary>()))
                 .Returns(() => virtualPathData);

            virtualPathData = new VirtualPathData(route.Object, "~/VirtualPath");

            routes = new RouteCollection();
            routes.Add(route.Object);

            originalRouteData = new RouteData();

            string returnValue = "";
            httpContext = new Mock<HttpContextBase>();
            httpContext.Expect(hc => hc.Request.ApplicationPath).Returns("~");
            httpContext.Expect(hc => hc.Response.ApplyAppPathModifier(It.IsAny<string>()))
                       .Callback<string>(s => returnValue = s)
                       .Returns(() => returnValue);
            httpContext.Expect(hc => hc.Server.Execute(It.IsAny<IHttpHandler>(), It.IsAny<TextWriter>(), It.IsAny<bool>()));

            viewContext = new ViewContext {
                RequestContext = new RequestContext(httpContext.Object, originalRouteData)
            };

            viewDataContainer = new Mock<IViewDataContainer>();

            htmlHelper = new Mock<HtmlHelper>(viewContext, viewDataContainer.Object, routes);
        }
开发者ID:consumentor,项目名称:Server,代码行数:28,代码来源:ChildActionExtensionsTest.cs

示例2: UserLogin_Steps

 public UserLogin_Steps()
 {
     var mock = new Mock<IAuthenticationService>();
     mock.Expect(x => x.IsValidLogin("admin", "password")).Returns(true);
     mock.Expect(x => x.IsValidLogin(It.IsAny<string>(),It.IsAny<string>())).Returns(false);
     _authService = mock.Object;
 }
开发者ID:dancoppock,项目名称:MVC3-Starter-Site,代码行数:7,代码来源:UserLogin_Steps.cs

示例3: BindModel

        public void BindModel() {
            // Arrange
            ControllerContext controllerContext = new ControllerContext();
            ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext() {
                ModelBinderProviders = new ModelBinderProviderCollection(),
                ModelMetadata = GetMetadataForObject(new Person()),
                ModelName = "someName"
            };

            Mock<IExtensibleModelBinder> mockDtoBinder = new Mock<IExtensibleModelBinder>();
            mockDtoBinder
                .Expect(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>()))
                .Returns(
                    delegate(ControllerContext cc, ExtensibleModelBindingContext mbc2) {
                        return true; // just return the DTO unchanged
                    });
            bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(ComplexModelDto), mockDtoBinder.Object, true /* suppressPrefixCheck */);

            Mock<TestableMutableObjectModelBinder> mockTestableBinder = new Mock<TestableMutableObjectModelBinder>() { CallBase = true };
            mockTestableBinder.Expect(o => o.EnsureModelPublic(controllerContext, bindingContext)).Verifiable();
            mockTestableBinder.Expect(o => o.GetMetadataForPropertiesPublic(controllerContext, bindingContext)).Returns(new ModelMetadata[0]).Verifiable();
            TestableMutableObjectModelBinder testableBinder = mockTestableBinder.Object;
            testableBinder.MetadataProvider = new DataAnnotationsModelMetadataProvider();

            // Act
            bool retValue = testableBinder.BindModel(controllerContext, bindingContext);

            // Assert
            Assert.IsTrue(retValue);
            Assert.IsInstanceOfType(bindingContext.Model, typeof(Person));
            Assert.IsTrue(bindingContext.ValidationNode.ValidateAllProperties);
            mockTestableBinder.Verify();
        }
开发者ID:pruiz,项目名称:AspMvc2,代码行数:33,代码来源:MutableObjectModelBinderTest.cs

示例4: ShouldCallSetBackgroundColorOnlyOnceWithNestedCallsToOnAndOff

        public void ShouldCallSetBackgroundColorOnlyOnceWithNestedCallsToOnAndOff()
        {
            // GIVEN
            var domContainer = new Mock<DomContainer>().Object;
            var nativeElementMock = new Mock<INativeElement>();
            var element = new Element(domContainer, nativeElementMock.Object);

            Settings.HighLightColor = "myTestColor";
            var highLight = new HighlightAction(element);

            nativeElementMock.Expect(nativeElement => nativeElement.IsElementReferenceStillValid()).Returns(true);
            nativeElementMock.Expect(nativeElement => nativeElement.GetStyleAttributeValue("backgroundColor")).Returns("initialColor").AtMostOnce();
            nativeElementMock.Expect(nativeElement => nativeElement.SetStyleAttributeValue("backgroundColor", "myTestColor")).AtMostOnce();
            nativeElementMock.Expect(nativeElement => nativeElement.SetStyleAttributeValue("backgroundColor", "initialColor")).AtMostOnce();

            // WHEN
            highLight.On();
            highLight.On();
            highLight.On();
            highLight.Off();
            highLight.Off();
            highLight.Off();

            // THEN
            nativeElementMock.VerifyAll();
        }
开发者ID:fschwiet,项目名称:watin_unbranched,代码行数:26,代码来源:HighlightActionTests.cs

示例5: GetFormHelper

        private static HtmlHelper GetFormHelper(out StringWriter writer) {
            Mock<HttpRequestBase> mockHttpRequest = new Mock<HttpRequestBase>();
            mockHttpRequest.Expect(r => r.Url).Returns(new Uri("http://www.contoso.com/some/path"));
            Mock<HttpResponseBase> mockHttpResponse = new Mock<HttpResponseBase>(MockBehavior.Strict);

            mockHttpResponse.Expect(r => r.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(r => AppPathModifier + r);
            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.Expect(c => c.Request).Returns(mockHttpRequest.Object);
            mockHttpContext.Expect(c => c.Response).Returns(mockHttpResponse.Object);
            RouteCollection rt = new RouteCollection();
            rt.Add(new Route("{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) });
            rt.Add("namedroute", new Route("named/{controller}/{action}/{id}", null) { Defaults = new RouteValueDictionary(new { id = "defaultid" }) });
            RouteData rd = new RouteData();
            rd.Values.Add("controller", "home");
            rd.Values.Add("action", "oldaction");

            Mock<ViewContext> mockViewContext = new Mock<ViewContext>();
            mockViewContext.Expect(c => c.HttpContext).Returns(mockHttpContext.Object);
            mockViewContext.Expect(c => c.RouteData).Returns(rd);
            writer = new StringWriter();
            mockViewContext.Expect(c => c.Writer).Returns(writer);

            HtmlHelper helper = new HtmlHelper(
                mockViewContext.Object,
                new Mock<IViewDataContainer>().Object,
                rt);
            return helper;
        }
开发者ID:pruiz,项目名称:AspMvc2,代码行数:28,代码来源:FormExtensionsTest.cs

示例6: ProcessRequestAddsServerHeaderCallsExecute

        public void ProcessRequestAddsServerHeaderCallsExecute() {
            // Arrange
            Mock<HttpContextBase> contextMock = new Mock<HttpContextBase>();
            Mock<HttpResponseBase> responseMock = new Mock<HttpResponseBase>();
            responseMock.Expect(r => r.AppendHeader(MvcHandler.MvcVersionHeaderName, "1.0")).Verifiable();
            contextMock.Expect(c => c.Response).Returns(responseMock.Object);

            RouteData rd = new RouteData();
            rd.Values.Add("controller", "foo");
            RequestContext requestContext = new RequestContext(contextMock.Object, rd);
            MvcHandler mvcHandler = new MvcHandler(requestContext);

            Mock<ControllerBase> controllerMock = new Mock<ControllerBase>();
            controllerMock.Protected().Expect("Execute", requestContext).Verifiable();

            ControllerBuilder cb = new ControllerBuilder();
            Mock<IControllerFactory> controllerFactoryMock = new Mock<IControllerFactory>();
            controllerFactoryMock.Expect(o => o.CreateController(requestContext, "foo")).Returns(controllerMock.Object);
            controllerFactoryMock.Expect(o => o.ReleaseController(controllerMock.Object));
            cb.SetControllerFactory(controllerFactoryMock.Object);
            mvcHandler.ControllerBuilder = cb;

            // Act
            mvcHandler.ProcessRequest(contextMock.Object);

            // Assert
            responseMock.Verify();
            controllerMock.Verify();
        }
开发者ID:sanyaade-mobiledev,项目名称:ASP.NET-Mvc-2,代码行数:29,代码来源:MvcHandlerTest.cs

示例7: FakeHttpContext

        public static HttpContextBase FakeHttpContext() {

            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();

            context.Expect(ctx => ctx.Request).Returns(request.Object);
            context.Expect(ctx => ctx.Response).Returns(response.Object);
            context.Expect(ctx => ctx.Session).Returns(session.Object);
            context.Expect(ctx => ctx.Server).Returns(server.Object);


            var form = new NameValueCollection();
            var querystring = new NameValueCollection();
            var cookies = new HttpCookieCollection();
            var user = new GenericPrincipal(new GenericIdentity("testuser"),new string[]{"Administrator"});
            
            request.Expect(r => r.Cookies).Returns(cookies);
            request.Expect(r => r.Form).Returns(form);
            request.Expect(q => q.QueryString).Returns(querystring);
            context.Expect(u => u.User).Returns(user);
            return context.Object;
        }
开发者ID:christattum,项目名称:MVC-Storefront,代码行数:25,代码来源:MVCMockHelper.cs

示例8: ProcessRequestWithNormalControlFlowForAsynchronousController

        public void ProcessRequestWithNormalControlFlowForAsynchronousController() {
            // Arrange
            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.ExpectMvcVersionResponseHeader().Verifiable();

            RequestContext requestContext = new RequestContext(mockHttpContext.Object, GetRouteData());
            MvcAsyncHandler handler = new MvcAsyncHandler(requestContext);

            MockAsyncResult asyncResult = new MockAsyncResult();
            Mock<IAsyncController> mockController = new Mock<IAsyncController>();
            mockController.Expect(c => c.BeginExecute(requestContext, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(asyncResult).Verifiable();
            mockController.Expect(c => c.EndExecute(asyncResult)).Verifiable();
            mockController.As<IDisposable>().Expect(c => c.Dispose()).AtMostOnce().Verifiable();

            ControllerBuilder builder = new ControllerBuilder();
            builder.SetControllerFactory(new SimpleControllerFactory(mockController.Object));
            handler.ControllerBuilder = builder;

            // Act
            IAsyncResult returnedAsyncResult = handler.BeginProcessRequest(mockHttpContext.Object, null, null);
            handler.EndProcessRequest(returnedAsyncResult);

            mockHttpContext.Verify();
            mockController.Verify();
        }
开发者ID:Marceli,项目名称:JQueryGridTest,代码行数:25,代码来源:MvcAsyncHandlerTest.cs

示例9: ExecuteCoreWithAsynchronousInvokerAndActionCompletesSuccessfully

        public void ExecuteCoreWithAsynchronousInvokerAndActionCompletesSuccessfully() {
            // Arrange
            ControllerContext controllerContext = GetControllerContext();
            MockAsyncResult asyncResult = new MockAsyncResult();

            Mock<ITempDataProvider> mockTempDataProvider = new Mock<ITempDataProvider>();
            mockTempDataProvider.Expect(p => p.LoadTempData(controllerContext)).Returns(new Dictionary<string, object>()).Verifiable();
            mockTempDataProvider.Expect(p => p.SaveTempData(controllerContext, It.IsAny<IDictionary<string, object>>())).AtMostOnce().Verifiable();

            Mock<IAsyncActionInvoker> mockInvoker = new Mock<IAsyncActionInvoker>();
            mockInvoker.Expect(i => i.BeginInvokeAction(controllerContext, "SomeAction", It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(asyncResult).Verifiable();
            mockInvoker.Expect(i => i.EndInvokeAction(asyncResult)).Returns(true).Verifiable();

            EmptyController controller = new EmptyController() {
                ControllerContext = controllerContext,
                TempDataProvider = mockTempDataProvider.Object,
                ActionInvoker = mockInvoker.Object
            };

            // Act
            IAsyncResult returnedAsyncResult = controller.BeginExecuteCore(null, null);
            controller.TempData["key"] = "value";
            controller.EndExecuteCore(returnedAsyncResult);

            // Assert
            mockInvoker.Verify();
            mockTempDataProvider.Verify();
        }
开发者ID:Marceli,项目名称:JQueryGridTest,代码行数:28,代码来源:AsyncControllerTest.cs

示例10: ConfigureRequest

		private IHttpRequest ConfigureRequest(string path)
		{
			var request = new Mock<IHttpRequest>();
			request.Expect(x => x.QueryString).Returns(new NameValueCollection());
			request.Expect(x => x.PathInfo).Returns(path);

			return request.Object;
		}
开发者ID:JonCanning,项目名称:ServiceStack,代码行数:8,代码来源:RestHandlerTests.cs

示例11: GetJsonEnabledControllerContext

        private static ControllerContext GetJsonEnabledControllerContext(string jsonString) {
            byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonString);
            MemoryStream jsonStream = new MemoryStream(jsonBytes);

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Expect(o => o.HttpContext.Request.ContentType).Returns("application/json");
            mockControllerContext.Expect(o => o.HttpContext.Request.InputStream).Returns(jsonStream);
            return mockControllerContext.Object;
        }
开发者ID:consumentor,项目名称:Server,代码行数:9,代码来源:JsonValueProviderFactoryTest.cs

示例12: ConfigureRequest

        private IHttpRequest ConfigureRequest(string path)
        {
            var request = new Mock<IHttpRequest>();
            request.Expect(x => x.Items).Returns(new Dictionary<string, object>());
            request.Expect(x => x.QueryString).Returns(PclExportClient.Instance.NewNameValueCollection());
            request.Expect(x => x.PathInfo).Returns(path);

            return request.Object;
        }
开发者ID:CLupica,项目名称:ServiceStack,代码行数:9,代码来源:RestHandlerTests.cs

示例13: GetEndpointAttributes_AcceptsUserHostAddressFormats

        public void GetEndpointAttributes_AcceptsUserHostAddressFormats(string format, EndpointAttributes expected)
        {
            var handler = new TestHandler();
            var request = new Mock<IHttpRequest>();
            request.Expect(req => req.UserHostAddress).Returns(format);
            request.Expect(req => req.IsSecureConnection).Returns(false);
            request.Expect(req => req.HttpMethod).Returns("GET");

            Assert.AreEqual(expected | EndpointAttributes.HttpGet | EndpointAttributes.InSecure, request.Object.GetAttributes());
        }
开发者ID:mcguinness,项目名称:ServiceStack,代码行数:10,代码来源:EndpointHandlerBaseTests.cs

示例14: GetStubRepo

        public static IUserAuthRepository GetStubRepo()
        {
            var mock = new Mock<IUserAuthRepository>();
            mock.Expect(x => x.GetUserAuthByUserName(It.IsAny<string>()))
                .Returns((UserAuth)null);
            mock.Expect(x => x.CreateUserAuth(It.IsAny<UserAuth>(), It.IsAny<string>()))
                .Returns(new UserAuth { Id = 1 });

            return mock.Object;
        }
开发者ID:AVee,项目名称:ServiceStack,代码行数:10,代码来源:RegistrationServiceTests.cs

示例15: ShouldSelectConstructorWithMostResolvableParametersFromTypeImplementation

        public void ShouldSelectConstructorWithMostResolvableParametersFromTypeImplementation()
        {
            var map = new Mock<IDependencyContainer>();
            map.Expect(m => m.Contains(It.IsAny<Dependency>())).Returns(true);
            map.Expect(m => m.Dependencies).Returns(new IDependency[] { });

            var expectedConstructor = typeof(Vehicle).GetConstructor(new Type[] { typeof(IPerson) });
            IImplementation<ConstructorInfo> implementation = new TransientType(typeof(Vehicle), map.Object, new ConstructorResolver());

            Assert.AreSame(implementation.Target, expectedConstructor);
        }
开发者ID:juancastrodlc,项目名称:Hiro,代码行数:11,代码来源:ImplementationTests.cs


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