예제 #1
0
        internal static string Render(DocumentConfiguration config, string view, object model)
        {
            var controller = new EmptyController();

            controller.ViewData.Model = model;

            var httpBase = new HttpContextWrapper(HttpContext.Current);
            var route    = new RouteData();

            route.Values.Add("controller", "value");
            var controllerContext = new ControllerContext(httpBase, route, controller);

            using (var sw = new StringWriter())
            {
                var viewResult = !string.IsNullOrWhiteSpace(config.MasterName) ?
                                 ViewEngines.Engines.FindView(controllerContext, view, config.MasterName) :
                                 ViewEngines.Engines.FindPartialView(controllerContext, view);

                var viewContext = new ViewContext(controllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);
                var result = sw.GetStringBuilder().ToString();

                return(result);
            }
        }
예제 #2
0
        public void ActionInvokerProperty() {
            // Arrange
            Controller controller = new EmptyController();

            // Act & Assert
            MemberHelper.TestPropertyWithDefaultInstance(controller, "ActionInvoker", new ControllerActionInvoker());
        }
예제 #3
0
        public void ExecuteCore_Asynchronous_ActionNotFound()
        {
            // Arrange
            MockAsyncResult innerAsyncResult = new MockAsyncResult();

            Mock <IAsyncActionInvoker> mockActionInvoker = new Mock <IAsyncActionInvoker>();

            mockActionInvoker.Setup(o => o.BeginInvokeAction(It.IsAny <ControllerContext>(), "SomeAction", It.IsAny <AsyncCallback>(), It.IsAny <object>())).Returns(innerAsyncResult);
            mockActionInvoker.Setup(o => o.EndInvokeAction(innerAsyncResult)).Returns(false);

            RequestContext  requestContext = GetRequestContext("SomeAction");
            EmptyController controller     = new EmptyController()
            {
                ActionInvoker = mockActionInvoker.Object
            };

            // Act & assert
            IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);

            Assert.False(controller.TempDataSaved);

            ((IAsyncController)controller).EndExecute(outerAsyncResult);
            Assert.True(controller.TempDataSaved);
            Assert.True(controller.HandleUnknownActionCalled);
        }
예제 #4
0
        public void ExecuteCore_SavesTempDataOnException()
        {
            // Arrange
            Mock <IAsyncActionInvoker> mockActionInvoker = new Mock <IAsyncActionInvoker>();

            mockActionInvoker
            .Setup(
                o =>
                o.BeginInvokeAction(
                    It.IsAny <ControllerContext>(),
                    "SomeAction",
                    It.IsAny <AsyncCallback>(),
                    It.IsAny <object>()
                    )
                )
            .Throws(new Exception("Some exception text."));

            RequestContext  requestContext = GetRequestContext("SomeAction");
            EmptyController controller     = new EmptyController()
            {
                ActionInvoker = mockActionInvoker.Object
            };

            // Act & assert
            Assert.Throws <Exception>(
                delegate
            {
                ((IAsyncController)controller).BeginExecute(requestContext, null, null);
            },
                @"Some exception text."
                );
            Assert.True(controller.TempDataSaved);
        }
예제 #5
0
        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();
        }
예제 #6
0
        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();
        }
예제 #7
0
            public void ProcessRequest(HttpContext context)
            {
                var    module = _rc.RouteData.Values["module"].ToString();
                var    method = _rc.RouteData.Values["method"].ToString();
                object id;

                _rc.RouteData.Values.TryGetValue("id", out id);
                //var urlHelper = new UrlHelper(_rc);

                var type = ModulesCatalog.GetModule(new HttpApplicationStateWrapper(context.Application), module, false);

                if (type == null)
                {
                    if (ModulesCatalog._ts.TraceInfo)
                    {
                        Debug.WriteLine("{0}: Cannot create type from module {1}", ModulesCatalog._ts.DisplayName, module);
                    }

                    return;
                }

                var r = type.CreateInstance((mtype, atype) =>
                {
                    if (typeof(UrlHelper).IsAssignableFrom(mtype) && !typeof(UrlHelper).IsAssignableFrom(atype))
                    {
                        return(new UrlHelper(_rc));
                    }

                    return(null);
                }) as IModuleHandler;

                if (r == null)
                {
                    if (ModulesCatalog._ts.TraceInfo)
                    {
                        Debug.WriteLine("{0}: Module {1} does not implement IModuleHandler", ModulesCatalog._ts.DisplayName, module);
                    }

                    return;
                }

                string view;

                if (!r.Call(method, id, _rc, out view))
                {
                    return;
                }

                _rc.RouteData.Values["controller"] = "Empty";
                using (var ctrl = new EmptyController())
                {
                    var cc = new ControllerContext(_rc, ctrl);
                    ctrl.Initialize(_rc, cc);
                    var ct = new ViewContext(cc, new View(), cc.Controller.ViewData, cc.Controller.TempData, context.Response.Output);
                    var h  = new HtmlHelper(ct, new ViewDataContainer(cc.Controller.ViewData));

                    context.Response.Output.Write(h.RenderModule(r, view).ToHtmlString());
                }
            }
예제 #8
0
        public void Execute_ThrowsIfRequestContextIsNull()
        {
            // Arrange
            IAsyncController controller = new EmptyController();

            // Act & assert
            Assert.ThrowsArgumentNull(
                delegate { controller.BeginExecute(null, null, null); }, "requestContext");
        }
        public void Execute_ThrowsIfRequestContextIsNull()
        {
            // Arrange
            IAsyncController controller = new EmptyController();

            // Act & assert
            Assert.ThrowsArgumentNull(
                delegate { controller.BeginExecute(null, null, null); }, "requestContext");
        }
예제 #10
0
        public void Execute_ThrowsIfRequestContextIsNull() {
            // Arrange
            IAsyncController controller = new EmptyController();

            // Act & assert
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                    controller.BeginExecute(null, null, null);
                }, "requestContext");
        }
예제 #11
0
        public void ActionInvokerProperty() {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            IActionInvoker invoker = controller.ActionInvoker;

            // Assert
            Assert.AreEqual(typeof(AsyncControllerActionInvoker), invoker.GetType());
        }
예제 #12
0
        public void AsyncManagerProperty() {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            AsyncManager asyncManager = controller.AsyncManager;

            // Assert
            Assert.IsNotNull(asyncManager);
        }
예제 #13
0
        public void ActionInvokerIsAsyncInvokerByDefault() {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            IActionInvoker invoker = controller.ActionInvoker;

            // Assert
            Assert.IsInstanceOfType(invoker, typeof(AsyncControllerActionInvoker));
        }
        public void ActionInvokerProperty()
        {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            IActionInvoker invoker = controller.ActionInvoker;

            // Assert
            Assert.IsType<AsyncControllerActionInvoker>(invoker);
        }
예제 #15
0
        public void AsyncManagerProperty()
        {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            AsyncManager asyncManager = controller.AsyncManager;

            // Assert
            Assert.NotNull(asyncManager);
        }
예제 #16
0
        public void ContentWithContentString() {
            // Arrange
            Controller controller = new EmptyController();
            string content = "Some content";

            // Act
            ContentResult result = controller.Content(content);

            // Assert
            Assert.AreEqual(content, result.Content);
        }
예제 #17
0
        public void ActionInvokerProperty()
        {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            IActionInvoker invoker = controller.ActionInvoker;

            // Assert
            Assert.AreEqual(typeof(AsyncControllerActionInvoker), invoker.GetType());
        }
예제 #18
0
        public void ExecuteThrowsIfRequestContextIsNull()
        {
            // Arrange
            IAsyncController controller = new EmptyController();

            // Act & assert
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                controller.BeginExecute(null, null, null);
            }, "requestContext");
        }
예제 #19
0
        public void ActionInvokerIsAsyncInvokerByDefault()
        {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            IActionInvoker invoker = controller.ActionInvoker;

            // Assert
            Assert.IsInstanceOfType(invoker, typeof(AsyncControllerActionInvoker));
        }
예제 #20
0
        public void ActionInvokerProperty()
        {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            IActionInvoker invoker = controller.ActionInvoker;

            // Assert
            Assert.IsType <AsyncControllerActionInvoker>(invoker);
        }
예제 #21
0
        public void Execute_ThrowsIfCalledMoreThanOnce()
        {
            // Arrange
            IAsyncController controller     = new EmptyController();
            RequestContext   requestContext = GetRequestContext("SomeAction");

            // Act & assert
            controller.BeginExecute(requestContext, null, null);
            Assert.Throws <InvalidOperationException>(
                delegate { controller.BeginExecute(requestContext, null, null); },
                @"A single instance of controller 'System.Web.Mvc.Test.AsyncControllerTest+EmptyController' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.");
        }
        public void OnAuthorizationSetsControllerValidateRequestToTrue() {
            // Arrange
            Controller controller = new EmptyController() { ValidateRequest = false };
            ValidateInputAttribute attr = new ValidateInputAttribute(enableValidation: true);
            AuthorizationContext authContext = GetAuthorizationContext(controller);

            // Act
            attr.OnAuthorization(authContext);

            // Assert
            Assert.IsTrue(controller.ValidateRequest);
        }
        public void Execute_ThrowsIfCalledMoreThanOnce()
        {
            // Arrange
            IAsyncController controller = new EmptyController();
            RequestContext requestContext = GetRequestContext("SomeAction");

            // Act & assert
            controller.BeginExecute(requestContext, null, null);
            Assert.Throws<InvalidOperationException>(
                delegate { controller.BeginExecute(requestContext, null, null); },
                @"A single instance of controller 'System.Web.Mvc.Test.AsyncControllerTest+EmptyController' cannot be used to handle multiple requests. If a custom controller factory is in use, make sure that it creates a new instance of the controller for each request.");
        }
예제 #24
0
        public void HttpContextProperty() {
            var c = new EmptyController();
            Assert.IsNull(c.HttpContext, "Property should be null before Context is set");

            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Setup(cc => cc.Controller).Returns(c);
            mockControllerContext.Setup(cc => cc.HttpContext).Returns(mockHttpContext.Object);

            c.ControllerContext = mockControllerContext.Object;
            Assert.AreEqual<HttpContextBase>(mockHttpContext.Object, c.HttpContext, "Property should equal the value on the Context.");
        }
예제 #25
0
        public void ContentWithContentStringAndContentType()
        {
            // Arrange
            Controller controller = new EmptyController();
            string content = "Some content";
            string contentType = "Some content type";

            // Act
            ContentResult result = controller.Content(content, contentType);

            // Assert
            Assert.Equal(content, result.Content);
            Assert.Equal(contentType, result.ContentType);
        }
예제 #26
0
        public void CreateActionInvokerCallsIntoResolverInstance()
        {
            // Controller uses an IDependencyResolver to create an IActionInvoker.
            var controller = new EmptyController();
            Mock <IDependencyResolver> resolverMock      = new Mock <IDependencyResolver>();
            Mock <IAsyncActionInvoker> actionInvokerMock = new Mock <IAsyncActionInvoker>();

            resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvoker))).Returns(actionInvokerMock.Object);
            controller.Resolver = resolverMock.Object;

            var ai = controller.CreateActionInvoker();

            resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvoker)), Times.Once());
            Assert.Same(actionInvokerMock.Object, ai);
        }
예제 #27
0
        public void ContentWithContentStringAndContentTypeAndEncoding() {
            // Arrange
            Controller controller = new EmptyController();
            string content = "Some content";
            string contentType = "Some content type";
            Encoding contentEncoding = Encoding.UTF8;

            // Act
            ContentResult result = controller.Content(content, contentType, contentEncoding);

            // Assert
            Assert.AreEqual(content, result.Content);
            Assert.AreEqual(contentType, result.ContentType);
            Assert.AreSame(contentEncoding, result.ContentEncoding);
        }
예제 #28
0
        public void CreateActionInvokerCallsIntoResolverInstanceAndCreatesANewOneIfNecessary()
        {
            // If IDependencyResolver is set, but empty, falls back and still creates.
            var controller = new EmptyController();
            Mock <IDependencyResolver> resolverMock = new Mock <IDependencyResolver>();

            resolverMock.Setup(r => r.GetService(typeof(IAsyncActionInvoker))).Returns(null);
            resolverMock.Setup(r => r.GetService(typeof(IActionInvoker))).Returns(null);
            controller.Resolver = resolverMock.Object;

            var ai = controller.CreateActionInvoker();

            resolverMock.Verify(r => r.GetService(typeof(IAsyncActionInvoker)), Times.Once());
            resolverMock.Verify(r => r.GetService(typeof(IActionInvoker)), Times.Once());
            Assert.NotNull(ai);
        }
        public void ReleaseController_ForwardsToUnderlyingFactory()
        {
            // Arrange
            EmptyController controller = new EmptyController();

            Mock <IControllerFactory> mockUnderlyingFactory = new Mock <IControllerFactory>();

            mockUnderlyingFactory.Expect(o => o.ReleaseController(controller)).Verifiable();
            MvcDynamicSessionControllerFactory factory = new MvcDynamicSessionControllerFactory(mockUnderlyingFactory.Object);

            // Act
            factory.ReleaseController(controller);

            // Assert
            mockUnderlyingFactory.Verify();
        }
예제 #30
0
        public void OnAuthorizationSetsControllerValidateRequestToTrue()
        {
            // Arrange
            Controller controller = new EmptyController()
            {
                ValidateRequest = false
            };
            ValidateInputAttribute attr        = new ValidateInputAttribute(enableValidation: true);
            AuthorizationContext   authContext = GetAuthorizationContext(controller);

            // Act
            attr.OnAuthorization(authContext);

            // Assert
            Assert.True(controller.ValidateRequest);
        }
예제 #31
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ViewRenderer" /> class.
        /// </summary>
        /// <param name="publishedRouter">The published router.</param>
        /// <param name="umbracoContextAccessor">The umbraco context accessor.</param>
        public ViewRenderer(IPublishedRouter publishedRouter, IUmbracoContextAccessor umbracoContextAccessor)
        {
            var controller = new EmptyController();
            var wrapper    = new HttpContextWrapper(HttpContext.Current);
            var routeData  = new RouteData
            {
                Values = { { "controller", "empty" } },
            };

            this.context = controller.ControllerContext = new ControllerContext(wrapper, routeData, controller);
            var context = umbracoContextAccessor.UmbracoContext;

            if (context.PublishedRequest?.PublishedContent == null)
            {
                context.PublishedRequest = publishedRouter.CreateRequest(context);
                context.PublishedRequest.PublishedContent = context.Content.GetAtRoot().FirstOrDefault();
            }
        }
        public void CreateCachedController_UnderlyingFactoryReturnsController() {
            // Arrange
            RequestContext requestContext = GetRequestContext();
            EmptyController controller = new EmptyController();

            Mock<IControllerFactory> mockUnderlyingFactory = new Mock<IControllerFactory>();
            mockUnderlyingFactory.Expect(o => o.CreateController(requestContext, "home")).Returns(controller).AtMostOnce();
            MvcDynamicSessionControllerFactory factory = new MvcDynamicSessionControllerFactory(mockUnderlyingFactory.Object);

            // Act
            IController controller1 = factory.CreateCachedController(requestContext, "home");
            IController controller2 = factory.CreateController(requestContext, "home");

            // Assert
            Assert.AreEqual(controller, controller1);
            Assert.AreSame(controller1, controller2);
            mockUnderlyingFactory.Verify();
        }
        public void ReleaseCachedController_ControllerInstanceCached_ReleasesInstance()
        {
            // Arrange
            RequestContext  requestContext = GetRequestContext();
            EmptyController controller     = new EmptyController();

            Mock <IControllerFactory> mockUnderlyingFactory = new Mock <IControllerFactory>();

            mockUnderlyingFactory.Expect(o => o.CreateController(requestContext, "home")).Returns(controller).AtMostOnce();
            mockUnderlyingFactory.Expect(o => o.ReleaseController(controller)).Verifiable();
            MvcDynamicSessionControllerFactory factory = new MvcDynamicSessionControllerFactory(mockUnderlyingFactory.Object);

            // Act
            factory.CreateCachedController(requestContext, "home");
            factory.ReleaseCachedController(requestContext.HttpContext);

            // Assert
            mockUnderlyingFactory.Verify();
        }
        public void CreateController_RemovesCachedController() {
            // Arrange
            RequestContext requestContext = GetRequestContext();
            EmptyController controller = new EmptyController();
            int numTimesCalled = 0;

            Mock<IControllerFactory> mockUnderlyingFactory = new Mock<IControllerFactory>();
            mockUnderlyingFactory.Expect(o => o.CreateController(requestContext, "home")).Returns(controller).Callback(() => { numTimesCalled++; });
            MvcDynamicSessionControllerFactory factory = new MvcDynamicSessionControllerFactory(mockUnderlyingFactory.Object);

            // Act & assert 1
            IController controller1 = factory.CreateCachedController(requestContext, "home");
            IController controller2 = factory.CreateController(requestContext, "home");
            Assert.AreEqual(1, numTimesCalled);

            // Act & assert 2
            IController controller3 = factory.CreateController(requestContext, "home");
            Assert.AreEqual(2, numTimesCalled);
        }
        public void CreateCachedController_UnderlyingFactoryReturnsController()
        {
            // Arrange
            RequestContext  requestContext = GetRequestContext();
            EmptyController controller     = new EmptyController();

            Mock <IControllerFactory> mockUnderlyingFactory = new Mock <IControllerFactory>();

            mockUnderlyingFactory.Expect(o => o.CreateController(requestContext, "home")).Returns(controller).AtMostOnce();
            MvcDynamicSessionControllerFactory factory = new MvcDynamicSessionControllerFactory(mockUnderlyingFactory.Object);

            // Act
            IController controller1 = factory.CreateCachedController(requestContext, "home");
            IController controller2 = factory.CreateController(requestContext, "home");

            // Assert
            Assert.AreEqual(controller, controller1);
            Assert.AreSame(controller1, controller2);
            mockUnderlyingFactory.Verify();
        }
예제 #36
0
        public void ExecuteCore_Asynchronous_ActionFound() {
            // Arrange
            MockAsyncResult innerAsyncResult = new MockAsyncResult();

            Mock<IAsyncActionInvoker> mockActionInvoker = new Mock<IAsyncActionInvoker>();
            mockActionInvoker.Setup(o => o.BeginInvokeAction(It.IsAny<ControllerContext>(), "SomeAction", It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);
            mockActionInvoker.Setup(o => o.EndInvokeAction(innerAsyncResult)).Returns(true);

            RequestContext requestContext = GetRequestContext("SomeAction");
            EmptyController controller = new EmptyController() {
                ActionInvoker = mockActionInvoker.Object
            };

            // Act & assert
            IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);
            Assert.IsFalse(controller.TempDataSaved, "TempData shouldn't have been saved yet.");

            ((IAsyncController)controller).EndExecute(outerAsyncResult);
            Assert.IsTrue(controller.TempDataSaved);
            Assert.IsFalse(controller.HandleUnknownActionCalled);
        }
예제 #37
0
        public void ExecuteCoreWithAsynchronousInvokerAndActionNotFound()
        {
            // 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(false).Verifiable();

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

            // Act
            IAsyncResult returnedAsyncResult = controller.BeginExecuteCore(null, null);

            controller.TempData["key"] = "value";
            ExceptionHelper.ExpectHttpException(
                delegate {
                controller.EndExecuteCore(returnedAsyncResult);
            },
                @"A public action method 'SomeAction' could not be found on controller 'Microsoft.Web.Mvc.Test.AsyncControllerTest+EmptyController'.",
                404);

            // Assert
            mockInvoker.Verify();
            mockTempDataProvider.Verify();
        }
        public void CreateController_RemovesCachedController()
        {
            // Arrange
            RequestContext  requestContext = GetRequestContext();
            EmptyController controller     = new EmptyController();
            int             numTimesCalled = 0;

            Mock <IControllerFactory> mockUnderlyingFactory = new Mock <IControllerFactory>();

            mockUnderlyingFactory.Expect(o => o.CreateController(requestContext, "home")).Returns(controller).Callback(() => { numTimesCalled++; });
            MvcDynamicSessionControllerFactory factory = new MvcDynamicSessionControllerFactory(mockUnderlyingFactory.Object);

            // Act & assert 1
            IController controller1 = factory.CreateCachedController(requestContext, "home");
            IController controller2 = factory.CreateController(requestContext, "home");

            Assert.AreEqual(1, numTimesCalled);

            // Act & assert 2
            IController controller3 = factory.CreateController(requestContext, "home");

            Assert.AreEqual(2, numTimesCalled);
        }
예제 #39
0
        public void ExecuteCoreWithAsynchronousInvokerAndBeginInvokeActionThrows()
        {
            // 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>();
            EmptyController            controller  = new EmptyController()
            {
                ControllerContext = controllerContext,
                TempDataProvider  = mockTempDataProvider.Object,
                ActionInvoker     = mockInvoker.Object
            };

            mockInvoker
            .Expect(i => i.BeginInvokeAction(controllerContext, "SomeAction", It.IsAny <AsyncCallback>(), It.IsAny <object>()))
            .Callback(
                delegate(ControllerContext cc, string an, AsyncCallback cb, object s) {
                controller.TempData["key"] = "value";
                throw new InvalidOperationException("Some exception text.");
            });

            // Act
            ExceptionHelper.ExpectInvalidOperationException(
                delegate {
                controller.BeginExecuteCore(null, null);
            },
                @"Some exception text.");

            // Assert
            mockTempDataProvider.Verify();
        }
예제 #40
0
        public void ExecuteCore_Synchronous_ActionNotFound()
        {
            // Arrange
            MockAsyncResult innerAsyncResult = new MockAsyncResult();

            Mock <IActionInvoker> mockActionInvoker = new Mock <IActionInvoker>();

            mockActionInvoker.Expect(o => o.InvokeAction(It.IsAny <ControllerContext>(), "SomeAction")).Returns(false);

            RequestContext  requestContext = GetRequestContext("SomeAction");
            EmptyController controller     = new EmptyController()
            {
                ActionInvoker = mockActionInvoker.Object
            };

            // Act & assert
            IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);

            Assert.IsFalse(controller.TempDataSaved, "TempData shouldn't have been saved yet.");

            ((IAsyncController)controller).EndExecute(outerAsyncResult);
            Assert.IsTrue(controller.TempDataSaved);
            Assert.IsTrue(controller.HandleUnknownActionCalled);
        }
예제 #41
0
        public void JsonWithBehavior() {
            // Arrange
            MyModel model = new MyModel();
            Controller controller = new EmptyController();

            // Act
            JsonResult result = controller.Json(model, JsonRequestBehavior.AllowGet);

            // Assert
            Assert.AreSame(model, result.Data);
            Assert.IsNull(result.ContentType);
            Assert.IsNull(result.ContentEncoding);
            Assert.AreEqual(JsonRequestBehavior.AllowGet, result.JsonRequestBehavior);
        }
예제 #42
0
 public void ContextProperty() {
     var controller = new EmptyController();
     MemberHelper.TestPropertyValue(controller, "ControllerContext", new Mock<ControllerContext>().Object);
 }
예제 #43
0
        public void FileWithStreamAndFileDownloadName() {
            // Arrange
            EmptyController controller = new EmptyController();
            Stream fileStream = Stream.Null;

            // Act
            FileStreamResult result = controller.File(fileStream, "someContentType", "someDownloadName");

            // Assert
            Assert.IsNotNull(result);
            Assert.AreSame(fileStream, result.FileStream);
            Assert.AreEqual("someContentType", result.ContentType);
            Assert.AreEqual("someDownloadName", result.FileDownloadName);
        }
예제 #44
0
 public void HandleUnknownActionThrows() {
     var controller = new EmptyController();
     ExceptionHelper.ExpectException<HttpException>(
         delegate {
             controller.HandleUnknownAction("UnknownAction");
         },
         "A public action method 'UnknownAction' was not found on controller 'System.Web.Mvc.Test.ControllerTest+EmptyController'.");
 }
예제 #45
0
        public void FileWithContentsAndFileDownloadName() {
            // Arrange
            EmptyController controller = new EmptyController();
            byte[] fileContents = new byte[0];

            // Act
            FileContentResult result = controller.File(fileContents, "someContentType", "someDownloadName");

            // Assert
            Assert.IsNotNull(result);
            Assert.AreSame(fileContents, result.FileContents);
            Assert.AreEqual("someContentType", result.ContentType);
            Assert.AreEqual("someDownloadName", result.FileDownloadName);
        }
예제 #46
0
        public void FileWithPathAndFileDownloadName() {
            // Arrange
            EmptyController controller = new EmptyController();

            // Act
            FilePathResult result = controller.File("somePath", "someContentType", "someDownloadName");

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual("somePath", result.FileName);
            Assert.AreEqual("someContentType", result.ContentType);
            Assert.AreEqual("someDownloadName", result.FileDownloadName);
        }
예제 #47
0
        public void JsonWithContentTypeAndEncodingAndBehavior() {
            // Arrange
            MyModel model = new MyModel();
            Controller controller = new EmptyController();

            // Act
            JsonResult result = controller.Json(model, "text/xml", Encoding.UTF32, JsonRequestBehavior.AllowGet);

            // Assert
            Assert.AreSame(model, result.Data);
            Assert.AreEqual("text/xml", result.ContentType);
            Assert.AreEqual(Encoding.UTF32, result.ContentEncoding);
            Assert.AreEqual(JsonRequestBehavior.AllowGet, result.JsonRequestBehavior);
        }
예제 #48
0
        public void RouteDataProperty() {
            var c = new EmptyController();
            Assert.IsNull(c.Request, "Property should be null before Context is set");

            RouteData rd = new RouteData();

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Setup(cc => cc.Controller).Returns(c);
            mockControllerContext.Setup(cc => cc.RouteData).Returns(rd);

            c.ControllerContext = mockControllerContext.Object;
            Assert.AreEqual(rd, c.RouteData, "Property should equal the value on the Context.");

        }
예제 #49
0
 private static Controller GetEmptyController() {
     ControllerContext context = GetControllerContext("Foo");
     var controller = new EmptyController() {
         ControllerContext = context,
         RouteCollection = new RouteCollection(),
         TempData = new TempDataDictionary(),
         TempDataProvider = new SessionStateTempDataProvider()
     };
     return controller;
 }
예제 #50
0
        public void SessionProperty() {
            var c = new EmptyController();
            Assert.IsNull(c.Request, "Property should be null before Context is set");

            Mock<HttpSessionStateBase> mockSessionState = new Mock<HttpSessionStateBase>();

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Setup(cc => cc.Controller).Returns(c);
            mockControllerContext.Setup(cc => cc.HttpContext.Session).Returns(mockSessionState.Object);

            c.ControllerContext = mockControllerContext.Object;
            Assert.AreEqual(mockSessionState.Object, c.Session, "Property should equal the value on the Context.");
        }
예제 #51
0
        public void UrlProperty() {
            // Arrange
            EmptyController controller = new EmptyController();
            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());

            // Act
            controller.PublicInitialize(requestContext);

            // Assert
            Assert.IsNotNull(controller.Url);
        }
예제 #52
0
        public void HttpNotFound() {
            // Arrange
            var c = new EmptyController();

            // Act
            HttpNotFoundResult result = c.HttpNotFound();

            // Assert
            Assert.IsNotNull(result);
            Assert.IsNull(result.StatusDescription);
            Assert.AreEqual(404, result.StatusCode);
        }
예제 #53
0
        public void UserProperty() {
            var c = new EmptyController();
            Assert.IsNull(c.Request, "Property should be null before Context is set");

            Mock<IPrincipal> mockUser = new Mock<IPrincipal>();

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Setup(cc => cc.Controller).Returns(c);
            mockControllerContext.Setup(cc => cc.HttpContext.User).Returns(mockUser.Object);

            c.ControllerContext = mockControllerContext.Object;
            Assert.AreEqual(mockUser.Object, c.User, "Property should equal the value on the Context.");
        }