public async void RedirectToRoute_Execute_PassesCorrectValuesToRedirect(object values)
        {
            // Arrange
            var expectedUrl = "SampleAction";
            var expectedPermanentFlag = false;
            var httpContext = new Mock<HttpContext>();
            var httpResponse = new Mock<HttpResponse>();
            httpContext.Setup(o => o.Response).Returns(httpResponse.Object);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ITempDataDictionary)))
                .Returns(Mock.Of<ITempDataDictionary>());

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

            var urlHelper = GetMockUrlHelper(expectedUrl);
            var result = new RedirectToRouteResult(null, TypeHelper.ObjectToDictionary(values))
            {
                UrlHelper = urlHelper,
            };

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            // Verifying if Redirect was called with the specific Url and parameter flag.
            // Thus we verify that the Url returned by UrlHelper is passed properly to
            // Redirect method and that the method is called exactly once.
            httpResponse.Verify(r => r.Redirect(expectedUrl, expectedPermanentFlag), Times.Exactly(1));
        }
        public void ConstructorSetsPermanent() {
            // Act
            var result = new RedirectToRouteResult(null, null, true);

            // Assert
            Assert.IsTrue(result.Permanent);
        }
 public void WithRouteName_GivenExpected_ShouldPass()
 {
     ActionResult result = new RedirectToRouteResult("default", null);
     result.Should()
             .BeRedirectToRouteResult()
             .WithRouteName("default");
 }
		public void WithPermanent_GivenExpected_ShouldPass()
		{
            ActionResult result = new RedirectToRouteResult("", null, true);
            result.Should()
                    .BeRedirectToRouteResult()
                    .WithPermanent(true);
		}
 public void WithPermanent_GivenUnExpected_ShouldFail()
 {
     ActionResult result = new RedirectToRouteResult("", null, true);
     Action a = () => result.Should()
             .BeRedirectToRouteResult()
             .WithPermanent(false);
     a.ShouldThrow<Exception>()
             .WithMessage("Expected RedirectToRoute.Permanent to be False, but found True");
 }
 public void WithRouteName_GivenUnExpected_ShouldFail()
 {
     ActionResult result = new RedirectToRouteResult("default", null);
     Action a = () => result.Should()
             .BeRedirectToRouteResult()
             .WithRouteName("xyz");
     a.ShouldThrow<Exception>()
         .WithMessage("Expected RedirectToRoute.RouteName to be \"xyz\", but found \"default\"");
 }
        public void ConstructorWithNullValuesDictionary() {
            // Act
            var result = new RedirectToRouteResult(null /* routeValues */);

            // Assert
            Assert.IsNotNull(result.RouteValues);
            Assert.AreEqual<int>(0, result.RouteValues.Count);
            Assert.AreEqual<string>(String.Empty, result.RouteName);
        }
        public void ConstructorWithNullValuesDictionary()
        {
            // Act
            var result = new RedirectToRouteResult(routeValues: null);

            // Assert
            Assert.NotNull(result.RouteValues);
            Assert.Empty(result.RouteValues);
            Assert.Equal(String.Empty, result.RouteName);
            Assert.False(result.Permanent);
        }
        public void ConstructorSetsValuesDictionaryAndName() {
            // Arrange
            RouteValueDictionary dict = new RouteValueDictionary();

            // Act
            var result = new RedirectToRouteResult("foo", dict);

            // Assert
            Assert.AreSame(dict, result.RouteValues);
            Assert.AreEqual<string>("foo", result.RouteName);
        }
        public void WithRouteValue_GivenExpected_ShouldPass()
        {
            ActionResult result = new RedirectToRouteResult("", new RouteValueDictionary(
                new
                {
                    Id = "22"
                }));

            result.Should()
                    .BeRedirectToRouteResult()
                    .WithRouteValue("Id", "22");
        }
        public void ConstructorSetsValuesDictionaryAndEmptyName() {
            // Arrange
            RouteValueDictionary dict = new RouteValueDictionary();

            // Act
            var result = new RedirectToRouteResult(null, dict);

            // Assert
            Assert.AreSame(dict, result.RouteValues);
            Assert.AreEqual<string>(String.Empty, result.RouteName);
            Assert.IsFalse(result.Permanent);
        }
        public void Execute(ActionContext context, RedirectToRouteResult result)
        {
            var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context);

            var destinationUrl = urlHelper.RouteUrl(result.RouteName, result.RouteValues);
            if (string.IsNullOrEmpty(destinationUrl))
            {
                throw new InvalidOperationException(Resources.NoRoutesMatched);
            }

            _logger.RedirectToRouteResultExecuting(destinationUrl, result.RouteName);
            context.HttpContext.Response.Redirect(destinationUrl, result.Permanent);
        }
        public void ExecuteResultThrowsIfVirtualPathDataIsNull() {
            // Arrange
            var result = new RedirectToRouteResult(null) {
                Routes = new RouteCollection()
            };

            // Act & Assert
            ExceptionHelper.ExpectException<InvalidOperationException>(
                delegate {
                    result.ExecuteResult(ControllerContextTest.CreateEmptyContext());
                },
                "No route in the route table matches the supplied values.");
        }
        public void ConstructorSetsValuesDictionaryAndName()
        {
            // Arrange
            RouteValueDictionary dict = new RouteValueDictionary();

            // Act
            var result = new RedirectToRouteResult("foo", dict);

            // Assert
            Assert.Same(dict, result.RouteValues);
            Assert.Equal("foo", result.RouteName);
            Assert.False(result.Permanent);
        }
        public void WithRouteValue_GivenUnexpected_ShouldFail()
        {
            ActionResult result = new RedirectToRouteResult("", new RouteValueDictionary(
                new
                {
                    Id = "22"
                }));

            Action a = () => result.Should()
                    .BeRedirectToRouteResult()
                    .WithRouteValue("Id", "11");
            a.ShouldThrow<Exception>()
                    .WithMessage("Expected dictionary to contain value \"11\" at key \"Id\", but found \"22\".");            
        }
        public void ExecuteResult() {
            // Arrange
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Expect(c => c.HttpContext.Request.ApplicationPath).Returns("/somepath");
            mockControllerContext.Expect(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);
            mockControllerContext.Expect(c => c.HttpContext.Response.Redirect("/somepath/c/a/i", false)).Verifiable();

            var values = new { Controller = "c", Action = "a", Id = "i" };
            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary(values)) {
                Routes = new RouteCollection() { new Route("{controller}/{action}/{id}", null) },
            };

            // Act
            result.ExecuteResult(mockControllerContext.Object);

            // Assert
            mockControllerContext.Verify();
        }
Example #17
0
        public static IUser Registation(string email, out ViewResult result, out RedirectToRouteResult redirectToRouteResult, string invite)
        {
            FormCollection collection = new FormCollection
            {
                { "email", email },
                { "password", email },
                { "confirmPassword", email },
                { "timezone", "0" }
            };
            var userController = Base.GetController <UserController>();

            result = (ViewResult)userController.Register(invite, null, collection);
            Repositories repositories = new Repositories(ConfigurationManager.ConnectionStrings["TimezConnectionString"].ConnectionString);
            IUser        user         = repositories.Users.GetByEmail(email);

            userController.Activate(user.ConfimKey);
            repositories.Dispose();
            userController        = Base.GetController <UserController>();
            redirectToRouteResult = (RedirectToRouteResult)userController.Login(null, email, email, false, null);

            return(user);
        }
Example #18
0
        public void Adding_Product_To_Cart_Goes_To_Cart_Screen()
        {
            //arrange
            Mock <IProductRepository> mock = new Mock <IProductRepository>();

            mock.Setup(p => p.Products).Returns(new Product[]
            {
                new Product {
                    ProductID = 1, Name = "P1", Category = "Jabłka"
                }
            }.AsQueryable());

            Cart           cart   = new Cart();
            CartController target = new CartController(mock.Object, null, null);

            //act
            RedirectToRouteResult result = target.AddToCart(cart, 2, "myUrl");

            //assert
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #19
0
        public void RedirectToActionOfT_WithMultipleParametersUsingRouteDictionarytParameter_ReturnsExpectedRedirectToRouteResult()
        {
            const string         expectedControllerName  = "RedirectToAction";
            const string         expectedActionName      = "MultipleParameters";
            const int            expectedId              = 3;
            const string         expectedOther           = "OtherValue";
            const string         expectedObjValue        = "object";
            const int            expectedRouteValueCount = 5;
            RouteValueDictionary routes = new RouteValueDictionary {
                { "obj", expectedObjValue }
            };
            MvcControllerBase     sut    = CreateSut();
            RedirectToRouteResult result = sut.RedirectToAction <RedirectToActionController>(controller => controller.MultipleParameters(expectedId, expectedOther), routes);

            Assert.IsNotNull(result);
            Assert.AreEqual(expectedRouteValueCount, result.RouteValues.Count);
            Assert.AreEqual(expectedControllerName, result.RouteValues["controller"]);
            Assert.AreEqual(expectedActionName, result.RouteValues["action"]);
            Assert.AreEqual(expectedId, result.RouteValues["id"]);
            Assert.AreEqual(expectedOther, result.RouteValues["other"]);
            Assert.AreEqual(expectedObjValue, result.RouteValues["obj"]);
        }
Example #20
0
        public void Adding_Movie_To_Cart_Goes_To_Cart_Screen()
        {
            // Arrange - create the mock repository
            Mock <IMovieRepository> mock = new Mock <IMovieRepository>();

            mock.Setup(m => m.Movies).Returns(new Movie[] { new Movie {
                                                                MovieID = 1, Name = "Movie 1", Category = "Action"
                                                            }, }.AsQueryable());

            // Arrange - create a Cart
            Cart cart = new Cart();

            // Arrange - create the controller
            CartController target = new CartController(mock.Object, null);

            // Act - add a Movie to the cart
            RedirectToRouteResult result = target.AddToCart(cart, 2, "myUrl");

            // Assert
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #21
0
        public void LogOn_Post_ReturnsRedirectToHomeOnSuccess_WithExternalReturnUrl()
        {
            // Arrange
            AccountController controller = GetAccountController();
            LogOnModel        model      = new LogOnModel()
            {
                UserName   = "******",
                Password   = "******",
                RememberMe = false
            };

            // Act
            ActionResult result = controller.LogOn(model, "http://malicious.example.net");

            // Assert
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            RedirectToRouteResult redirectResult = (RedirectToRouteResult)result;

            Assert.AreEqual("Home", redirectResult.RouteValues["controller"]);
            Assert.AreEqual("Index", redirectResult.RouteValues["action"]);
            Assert.IsTrue(((MockFormsAuthenticationService)controller.FormsService).SignIn_WasCalled);
        }
Example #22
0
        public void AddToOrder_UnauthenicatedUser()
        {
            CartController cosController = new CartController();

            var mockPrincipal = new Mock <IPrincipal>();

            mockPrincipal.Setup(x => x.Identity.IsAuthenticated).Returns(false);

            var mockContext = new Mock <ControllerContext>();

            mockContext.Setup(p => p.HttpContext.User).Returns(mockPrincipal.Object);
            cosController.ControllerContext = mockContext.Object;


            var result = cosController.AddToOrder(0);

            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            RedirectToRouteResult redirect = (RedirectToRouteResult)result;

            Assert.AreEqual("Account", redirect.RouteValues["controller"]);
            Assert.AreEqual("Login", redirect.RouteValues["action"]);
        }
Example #23
0
        public void Adding_Book_To_Cart_Goes_To_Cart_Screen()
        {
            //Arrange
            Mock <IBookRepository> mock = new Mock <IBookRepository>();

            mock.Setup(m => m.Books).Returns(
                new Book[]
            {
                new Book {
                    BookId = 1, Title = "ASP.NET MVC", Specialization = "Programming"
                }
            }.AsQueryable()
                );
            Cart           cart   = new Cart();
            CartController target = new CartController(mock.Object, null);
            //Act
            RedirectToRouteResult result = target.AddToCart(cart, 2, "myUrl");

            //Assert
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #24
0
        public void Add_New_User_Test()
        {
            //Arrange
            UsersController controller = new UsersController();
            Users           user       = new Users()
            {
                FirstName     = "Haoyue",
                LastName      = "Wang",
                Gender        = "Female",
                Phone         = "647906123",
                Email         = "*****@*****.**",
                AddressId     = 1,
                Membership_Id = 1
            };
            string expectedViewName = "Index";
            //Act
            RedirectToRouteResult result = controller.Create(user) as RedirectToRouteResult;
            string actualViewName        = result.RouteValues["Action"].ToString();

            //Assert
            Assert.AreEqual(expectedViewName, actualViewName);
        }
        public void EditSavePass()
        {
            // arrange
            var album = new Album()
            {
                AlbumId = 4,
                Title   = "Album 4",
                Price   = 44
            };

            // act
            RedirectToRouteResult actual = (RedirectToRouteResult)controller.Edit(album);

            // assert
            Assert.AreEqual("Index", actual.RouteValues["action"]);

            //// act
            //var actual = (RedirectToRouteResult)controller.Edit(album);

            //// assert
            //Assert.AreEqual("Index", actual.RouteValues["action"]);
        }
Example #26
0
        public void Adding_Hsuit_To_Cart_Goes_To_Cart_Screen()
        {
            //Setup - Create of repository imitation, Cart, CartController

            repo.Setup(h => h.Hsuits).Returns(new List <Hsuit>
            {
                new Hsuit {
                    Id = 1, Name = "Hsuit1", Category = "cat1"
                }
            }.AsQueryable());

            Cart cart = new Cart();

            CartController controller = new CartController(repo.Object, orderProcessor.Object, mailService.Object);

            // Action - Add object to cart
            RedirectToRouteResult result = controller.AddToCart(cart, 1, "backToShop");

            //Assert
            Assert.AreEqual(result.RouteValues["Action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "backToShop");
        }
Example #27
0
        public ActionResult Delete(int id)
        {
            this.allowedRoles.Add(this.ROLE_MANAGER);
            RedirectToRouteResult redirectToHome = this.RouteAccessAllowedRoles();

            if (redirectToHome != null)
            {
                return(redirectToHome);
            }

            ActivityDateManager adm          = new ActivityDateManager();
            ActivityDate        activityDate = adm.GetActivityDateById(id);

            adm.DeleteActivityDateById(id);

            int activityId = (int)activityDate.ActivityId;

            ActivityManager am       = new ActivityManager();
            Activity        activity = am.GetActivityById(activityId);

            return(RedirectToAction("Edit", "Activity", new { id = activity.Id }));
        }
        public void CreateModelStateValid()
        {
            // Arrange
            long newNoteId = 77777;

            SetTestUserName(notebook1.Email);

            Note aNewNote = new Note();

            aNewNote.NoteId   = newNoteId;
            aNewNote.NoteText = "This is a new note entry";
            aNewNote.Subject  = "Test Note";

            // Act
            RedirectToRouteResult result = (RedirectToRouteResult)controller.Create(aNewNote);

            // Assert
            Assert.AreEqual("Notebook", result.RouteValues["action"].ToString());

            Assert.IsTrue(noteList.Contains(aNewNote));
            Assert.AreEqual(aNewNote.NoteId, notebook1.CurrentNote);
        }
Example #29
0
        public void EditRegisterReturnRedirect()
        {
            var mockCourse   = new Mock <ICourseRepository>();
            var mockRegister = new Mock <IRegisterRepository>();
            var register     = new Register {
                Course = new Course {
                    CourseId = 1
                }, Mark = 5
            };
            var registerViewModel = new RegisterViewModel {
                RegisterId = 21, Mark = 5
            };
            LecturerController controller = new LecturerController(mockCourse.Object, mockRegister.Object);

            mockRegister.Setup(r => r.Get(registerViewModel.RegisterId)).Returns(register).Verifiable();
            mockRegister.Setup(r => r.Update(register));

            RedirectToRouteResult result = controller.EditRegister(registerViewModel) as RedirectToRouteResult;

            Assert.AreEqual(result.GetType(), typeof(RedirectToRouteResult));
            Assert.AreEqual(result.RouteValues["id"], 1);
        }
        public void Register_Post_ReturnsRedirectOnSuccess()
        {
            // Arrange
            AccountController controller = GetAccountController();
            RegisterModel     model      = new RegisterModel()
            {
                UserName        = "******",
                Email           = "goodEmail",
                Password        = "******",
                ConfirmPassword = "******"
            };

            // Act
            ActionResult result = controller.Register(model);

            // Assert
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            RedirectToRouteResult redirectResult = (RedirectToRouteResult)result;

            Assert.AreEqual("Home", redirectResult.RouteValues["controller"]);
            Assert.AreEqual("Index", redirectResult.RouteValues["action"]);
        }
Example #31
0
        public void LogOn_Post_ReturnsRedirectOnSuccess_WithoutReturnUrl()
        {
            // 排列
            AccountController controller = GetAccountController();
            LogOnModel        model      = new LogOnModel()
            {
                UserName   = "******",
                Password   = "******",
                RememberMe = false
            };

            // 作用
            ActionResult result = controller.LogOn(model, null);

            // 判斷提示
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            RedirectToRouteResult redirectResult = (RedirectToRouteResult)result;

            Assert.AreEqual("Home", redirectResult.RouteValues["controller"]);
            Assert.AreEqual("Index", redirectResult.RouteValues["action"]);
            Assert.IsTrue(((MockFormsAuthenticationService)controller.FormsService).SignIn_WasCalled);
        }
Example #32
0
        public void Adding_Product_To_Cart_Goes_To_Cart_Screen()
        {
            // Arrange - create the mock repository
            Mock <IProductRepository> mock = new Mock <IProductRepository>();

            mock.Setup(m => m.Products).Returns(new Product[] { new Product {
                                                                    ProductID = 1, Name = "P1", Category = "Apples"
                                                                } }.AsQueryable());
            // Arrange - create the mock processor
            Mock <IOrderProcessor> mockP = new Mock <IOrderProcessor>();
            // Arrange - create a Cart
            Cart cart = new Cart();
            // Arrange - create the controller
            CartController target = new CartController(mock.Object, mockP.Object);

            // Act - add a product to the cart
            RedirectToRouteResult result = target.AddToCart(cart, 2, "myUrl");

            // Assert
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #33
0
        public void TestAddToCartRedirect()
        {
            // Arrange
            Mock <IProductRepository> mockBuilder = new Mock <IProductRepository>();

            mockBuilder.Setup(m => m.Products).Returns(new Product[] {
                new Product {
                    ProductId = 1, Name = "P1", Category = "Apples"
                }
            });

            Cart cart = new Cart();

            CartController cartController = new CartController(mockBuilder.Object, null);

            // Act
            RedirectToRouteResult result = cartController.AddToCart(cart, 2, "myUrl");

            // Assert
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #34
0
        public void AddToCart_AddProductToCart_Goes_ToCartScreen()
        {
            //Arrange
            Mock <IProductRepository> mock = new Mock <IProductRepository>();

            mock.Setup(m => m.Products).Returns(new Product[]
            {
                new Product {
                    ProductId = 1, Name = "P1", Category = "Cat1"
                },
            }.AsQueryable());

            Cart           cart       = new Cart();
            CartController controller = new CartController(mock.Object, null);

            //Act
            RedirectToRouteResult result = controller.AddToCart(cart, 2, "myUrl");

            //Assert
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #35
0
        public void RedirectToRoute_Execute_ThrowsOnNullUrl()
        {
            // Arrange
            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(o => o.Response).Returns(new Mock<HttpResponse>().Object);
            var actionContext = new ActionContext(httpContext.Object,
                                                  new RouteData(),
                                                  new ActionDescriptor());

            IUrlHelper urlHelper = GetMockUrlHelper(returnValue: null);
            RedirectToRouteResult result = new RedirectToRouteResult(urlHelper, 
                                                                     null,
                                                                     new Dictionary<string, object>());

            // Act & Assert
            ExceptionAssert.ThrowsAsync<InvalidOperationException>(
                async () =>
                {
                    await result.ExecuteResultAsync(actionContext);
                },
                "No route matches the supplied values.");
        }
Example #36
0
        public void Adding_Product_To_Cart_Goes_To_CartScreen()
        {
            //Arrange
            Mock <IProductRepository> mock = new Mock <IProductRepository>();

            mock.Setup(m => m.Products).Returns(new Product[] {
                new Product {
                    ProductID = 1, Name = "P1", Category = "Apples"
                }
            }.AsQueryable());

            Cart           cart   = new Cart();
            CartController target = new CartController(mock.Object, null);

            //Act
            RedirectToRouteResult result = target.AddToCart(cart, 2, "myUrl");

            //Assert
            //Assert.AreEqual(result.RouteValues["controller"], "CartController");  //此时没有指定controller,内部机制必定会在哪里加载默认controller的
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
        public void IndexWithoutData()
        {
            var mockUser = new User()
            {
                UID = "e100"
            };
            var mockData  = new List <StickerApplication>();
            var mockDbSet = new Mock <DbSet <StickerApplication> >().SetupData(mockData);
            var dbctx     = new Mock <DatabaseContext>();

            dbctx.Setup(c => c.StickerApplications).Returns(mockDbSet.Object);

            StickerController controller = new StickerController(dbctx.Object);

            controller.ControllerContext = new ControllerContext(MockAuthContext(mockUser).Object, new RouteData(), controller);

            RedirectToRouteResult result = controller.Index() as RedirectToRouteResult;

            Assert.IsNotNull(result);
            Assert.AreEqual("action", result.RouteValues.Keys.FirstOrDefault());
            Assert.AreEqual("Apply", result.RouteValues.Values.FirstOrDefault());
        }
Example #38
0
        public void Adding_Product_To_Cart_Goes_To_Cart_Screen()
        {
            //将一个产品添加到购物车之后,URL应该被正确地传递给Index动作方法
            Mock <IProductsRepository> mock = new Mock <IProductsRepository>();

            mock.Setup(m => m.Products).Returns(new Product[]
            {
                new Product {
                    ProductID = 1, Name = "P1", Category = "Apples"
                }
            }.AsQueryable());

            Cart cart = new Cart();

            CartController target = new CartController(mock.Object, null);

            RedirectToRouteResult result = target.AddToCart(cart, 2, "myUrl");

            //断言
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #39
0
        public void Adding_Game_To_Goes_To_Cart_Screen()
        {
            // arrange
            Mock <IGameRepository> mock = new Mock <IGameRepository>();

            mock.Setup(m => m.Games).Returns(new List <Game> {
                new Game {
                    GameId = 1, Name = "Game_1", Category = "Cat_1"
                }
            }.AsQueryable());

            Cart cart = new Cart();

            CartController controller = new CartController(mock.Object, null);

            // act
            RedirectToRouteResult result = controller.AddToCart(cart, 2, "myUrl");

            // assers
            Assert.AreEqual(result.RouteValues["action"], "Index");
            Assert.AreEqual(result.RouteValues["returnUrl"], "myUrl");
        }
Example #40
0
        public void ExecuteResultPreservesTempData()
        {
            // Arrange
            TempDataDictionary tempData = new TempDataDictionary();

            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";
            Mock <Controller> mockController = new Mock <Controller>()
            {
                CallBase = true
            };

            mockController.Object.TempData = tempData;
            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext.Setup(c => c.HttpContext.Request.ApplicationPath).Returns("/somepath");
            mockControllerContext.Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny <string>())).Returns((string s) => s);
            mockControllerContext.Setup(c => c.HttpContext.Response.Redirect("/somepath/c/a/i", false)).Verifiable();
            mockControllerContext.Setup(c => c.Controller).Returns(mockController.Object);

            var values = new { Controller = "c", Action = "a", Id = "i" };
            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary(values))
            {
                Routes = new RouteCollection()
                {
                    new Route("{controller}/{action}/{id}", null)
                },
            };

            // Act
            object value = tempData["Foo"];

            result.ExecuteResult(mockControllerContext.Object);
            mockController.Object.TempData.Save(mockControllerContext.Object, new Mock <ITempDataProvider>().Object);

            // Assert
            Assert.IsTrue(tempData.ContainsKey("Foo"));
            Assert.IsTrue(tempData.ContainsKey("Bar"));
        }
Example #41
0
        public async void GetIndex_NoOrganisations_RedirectsToCreateJoinOrganisation()
        {
            // Arrange
            IWeeeClient weeeClient = A.Fake <IWeeeClient>();

            A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetUserOrganisationsByStatus> ._))
            .Returns(new List <OrganisationUserData>());

            OrganisationController controller = new OrganisationController(() => weeeClient);

            // Act
            ActionResult result = await controller.Index();

            // Assert
            Assert.IsAssignableFrom <RedirectToRouteResult>(result);

            RedirectToRouteResult redirectResult = result as RedirectToRouteResult;

            Assert.Equal(null, redirectResult.RouteValues["area"] as string, ignoreCase: true);
            Assert.Equal("organisationregistration", redirectResult.RouteValues["controller"] as string, ignoreCase: true);
            Assert.Equal("Search", redirectResult.RouteValues["action"] as string, ignoreCase: true);
        }
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            object usuarioLogado = filterContext.HttpContext.Session["Voluntario"];

            if (usuarioLogado == null)
            {
                usuarioLogado = filterContext.HttpContext.Session["Entidade"];
                if (usuarioLogado == null)
                {
                    usuarioLogado = filterContext.HttpContext.Session["Governo"];
                }
            }


            if (usuarioLogado == null)
            {
                RouteValueDictionary  dicionario        = new RouteValueDictionary(new { action = "Index", Controller = "Login" });
                RedirectToRouteResult rotaRedirecionada = new RedirectToRouteResult(dicionario);

                filterContext.Result = rotaRedirecionada;
            }
        }
Example #43
0
        public void CanCreateValidHostFromForm()
        {
            // Establish Context
            var hostFromForm = new Host();
            var testUser     = new Person();

            testUser.SetAssignedIdTo(1);
            _authenticationProvider.Expect(r => r.GetLoggedInUser()).Return("user1");
            _personManagementService.Expect(r => r.GetByUserName("user1")).Return(testUser);

            hostManagementService.Expect(r => r.SaveOrUpdate(hostFromForm))
            .Return(ActionConfirmation.CreateSuccessConfirmation("saved"));

            // Act
            RedirectToRouteResult redirectResult =
                hostsController.Create(hostFromForm)
                .AssertActionRedirect().ToAction("Search");

            // Assert
            hostsController.TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()].ToString()
            .ShouldEqual("saved");
        }
        public void AddNewQuestion_Post_Valid()
        {
            // Arrange
            var controller = new AssessmentController(_ITrainingService, _IAssessmentService);

            //Initialize model
            AssessmentViewModel assessmentViewModel = new AssessmentViewModel();

            assessmentViewModel.AssessmentPaper = new AssessmentPaperViewModel();
            assessmentViewModel.AssessmentPaper.AssessmentPaperId = 1;
            assessmentViewModel.AssessmentQuestions = new List <AssessmentQuestionsViewModel>();
            AssessmentQuestionsViewModel assessmentQuestionsViewModel = new AssessmentQuestionsViewModel();

            assessmentQuestionsViewModel.QuestionId         = 0;
            assessmentQuestionsViewModel.Question           = "a";
            assessmentQuestionsViewModel.Option1Description = "a1";
            assessmentQuestionsViewModel.IsOption1Correct   = true;
            assessmentQuestionsViewModel.Option2Description = "a1";
            assessmentQuestionsViewModel.IsOption2Correct   = true;
            assessmentQuestionsViewModel.Option3Description = "a1";
            assessmentQuestionsViewModel.IsOption3Correct   = true;
            assessmentQuestionsViewModel.Option4Description = "a1";
            assessmentQuestionsViewModel.IsOption4Correct   = true;
            assessmentQuestionsViewModel.CreatedBy          = 1;
            assessmentQuestionsViewModel.CreatedOn          = DateTime.Now;
            assessmentQuestionsViewModel.LastEditedBy       = 1;
            assessmentQuestionsViewModel.LastEditedOn       = DateTime.Now;
            assessmentQuestionsViewModel.IsActive           = true;
            assessmentViewModel.AssessmentQuestions.Add(assessmentQuestionsViewModel);

            //Act
            var result = (ActionResult)controller.AddNewQuestion(assessmentViewModel);

            //Assert
            Assert.IsInstanceOfType(result, typeof(RedirectToRouteResult));
            RedirectToRouteResult routeResult = result as RedirectToRouteResult;

            Assert.AreEqual(routeResult.RouteValues["action"], "ShowAssessmentPaperDetails");
        }
Example #45
0
        public void CanCreateValidRequestTypeFromForm()
        {
            // Establish Context
            var requestTypeFromForm = new RequestType();
            var testUser            = PersonInstanceFactory.CreateValidTransientPerson();

            testUser.SetAssignedIdTo(1);

            _authenticationProvider.Expect(r => r.GetLoggedInUser()).Return("testuser");
            _personManagementService.Expect(r => r.GetByUserName(Arg <string> .Is.Anything)).Return(testUser);
            _requestTypeManagementService.Expect(r => r.SaveOrUpdate(requestTypeFromForm))
            .Return(ActionConfirmation.CreateSuccessConfirmation("saved"));

            // Act
            RedirectToRouteResult redirectResult =
                _requestTypesController.Create(requestTypeFromForm)
                .AssertActionRedirect().ToAction("Index");

            // Assert
            _requestTypesController.TempData[ControllerEnums.GlobalViewDataProperty.PageMessage.ToString()].ToString()
            .ShouldEqual("saved");
        }
Example #46
0
        public async Task ExportsController_SaveTemplate()
        {
            AuthenticationHelper.HttpContext = AuthenticationHelper.CreateHttpContext(true);
            ExportsController controller = new ExportsController();

            SetupController(controller);

            //ExportsViewModel defaultExportViewModel = await GetDefaultExportsViewModel();
            DateTime         currentTime            = DateTime.UtcNow;
            ExportsViewModel defaultExportViewModel = await GetDefaultExportsViewModel();

            defaultExportViewModel.NewTemplateName       = string.Format("[UNIT TEST TEMPLATE]-{0}", currentTime);
            defaultExportViewModel.NewTemplateVendorName = string.Format("[UNIT TEST VENDOR]-{0}", currentTime);
            var result = controller.SaveTemplate(defaultExportViewModel);

            Assert.IsNotNull(result, "Invalid result");
            if (result is RedirectToRouteResult)
            {
                RedirectToRouteResult redirecResult = result as RedirectToRouteResult;
                Assert.IsTrue(redirecResult.RouteValues["action"].ToString() == "Index" && redirecResult.RouteValues["controller"].ToString() == "Templates");
            }
            else
            {
                Assert.Fail("Unexpected result");
            }
            var templateToDelete = AuthenticationHelper.DB.Templates.Where(p => p.VendorName ==
                                                                           defaultExportViewModel.NewTemplateVendorName && p.TemplateName == defaultExportViewModel.NewTemplateName).FirstOrDefault();

            if (templateToDelete != null)
            {
                AuthenticationHelper.DB.Templates.Remove(templateToDelete);
                if (
                    AuthenticationHelper.DB.SaveChanges() == 0)
                {
                    Assert.Fail("Unable to delete template: " + defaultExportViewModel.NewTemplateName);
                }
            }
        }
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext == null)
            {
                throw new ArgumentNullException("filterContext");
            }
            string Url = ((System.Web.HttpContextBase)filterContext.RequestContext.HttpContext).Request.Url.ToString();//当前页面地址

            string ToUrl = ((System.Web.HttpContextBase)filterContext.RequestContext.HttpContext).Request.Url.ToString();

            //ToUrl = DealMvc.DBUtility.DESEncrypt.Encrypt(ToUrl);

            ActionResult Result =
                new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new
            {
                controller = "User",
                action     = "Login",
                ToUrl      = ((System.Web.HttpContextBase)filterContext.RequestContext.HttpContext).Request.Url.ToString()//当前页面地址
            }));

            //判断是否登录
            //Model.Member m_UUser = new Model.Member();
            //if (!Common.Globals.isUserLogin())
            //{
            //    filterContext.Result = Result;
            //    return;
            //}
            //else
            //{
            //    m_UUser = Model.Member.GetModel(t => t.M_UID == Common.Globals.getUserName() && t.M_IsLock == false);
            //}

            //if (m_UUser.IsNull)
            //{//判断是否登录
            //    filterContext.Result = Result;
            //    return;
            //}
        }
        public void ExecuteResultPreservesTempData() {
            // Arrange
            TempDataDictionary tempData = new TempDataDictionary();
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";
            Mock<Controller> mockController = new Mock<Controller>() { CallBase = true };
            mockController.Object.TempData = tempData;
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Expect(c => c.HttpContext.Request.ApplicationPath).Returns("/somepath");
            mockControllerContext.Expect(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);
            mockControllerContext.Expect(c => c.HttpContext.Response.Redirect("/somepath/c/a/i", false)).Verifiable();
            mockControllerContext.Expect(c => c.Controller).Returns(mockController.Object);

            var values = new { Controller = "c", Action = "a", Id = "i" };
            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary(values)) {
                Routes = new RouteCollection() { new Route("{controller}/{action}/{id}", null) },
            };

            // Act
            object value = tempData["Foo"];
            result.ExecuteResult(mockControllerContext.Object);
            mockController.Object.TempData.Save(mockControllerContext.Object, new Mock<ITempDataProvider>().Object);

            // Assert
            Assert.IsTrue(tempData.ContainsKey("Foo"));
            Assert.IsTrue(tempData.ContainsKey("Bar"));
        }
        public void WithAction_GivenExpected_ShouldPass()
        {
            ActionResult result = new RedirectToRouteResult("", new RouteValueDictionary(
                new
                {
                    Action = "index"
                }));

            result.Should()
                    .BeRedirectToRouteResult()
                    .WithAction("index");
        }
        public void RedirectInChildActionThrows() {
            // Arrange
            RouteData routeData = new RouteData();
            routeData.DataTokens[ControllerContext.PARENT_ACTION_VIEWCONTEXT] = new ViewContext();
            ControllerContext context = new ControllerContext(new Mock<HttpContextBase>().Object, routeData, new Mock<ControllerBase>().Object);
            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary());

            // Act & Assert
            ExceptionHelper.ExpectInvalidOperationException(
                () => result.ExecuteResult(context),
                MvcResources.RedirectAction_CannotRedirectInChildAction
            );
        }
        public void WithArea_GivenUnexpected_ShouldFail()
        {
            ActionResult result = new RedirectToRouteResult("", new RouteValueDictionary(
                new
                {
                    Area = "accounts"
                }));

            Action a = () => result.Should()
                    .BeRedirectToRouteResult()
                    .WithArea("xyz");
            a.ShouldThrow<Exception>()
                    .WithMessage("Expected dictionary to contain value \"xyz\" at key \"Area\", but found \"accounts\".");
        }
        public void RoutesPropertyDefaultsToGlobalRouteTable() {
            // Act
            var result = new RedirectToRouteResult(new RouteValueDictionary());

            // Assert
            Assert.AreSame(RouteTable.Routes, result.Routes);
        }
        public void ExecuteResultWithNullControllerContextThrows() {
            // Arrange
            var result = new RedirectToRouteResult(null);

            // Act & Assert
            ExceptionHelper.ExpectArgumentNullException(
                delegate {
                    result.ExecuteResult(null /* context */);
                },
                "context");
        }
        public void WithController_GivenExpected_ShouldPass()
        {
            ActionResult result = new RedirectToRouteResult("", new RouteValueDictionary(
                new
                {
                    Controller = "home"
                }));

            result.Should()
                    .BeRedirectToRouteResult()
                    .WithController("home");
        }
        public void RedirectInChildActionThrows()
        {
            // Arrange
            RouteData routeData = new RouteData();
            routeData.DataTokens[ControllerContext.ParentActionViewContextToken] = new ViewContext();
            ControllerContext context = new ControllerContext(new Mock<HttpContextBase>().Object, routeData, new Mock<ControllerBase>().Object);
            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary());

            // Act & Assert
            Assert.Throws<InvalidOperationException>(
                () => result.ExecuteResult(context),
                "Child actions are not allowed to perform redirect actions.");
        }
 public void BeRedirectToRoute_GivenRedirectToRoute_ShouldPass()
 {
     ActionResult result = new RedirectToRouteResult(new RouteValueDictionary());
     result.Should().BeRedirectToRouteResult();
 }
        public void RedirectToRoute_Execute_Calls_TempDataKeep()
        {
            // Arrange
            var tempData = new Mock<ITempDataDictionary>();
            tempData.Setup(t => t.Keep()).Verifiable();

            var httpContext = new Mock<HttpContext>();
            httpContext.Setup(o => o.Response).Returns(new Mock<HttpResponse>().Object);
            httpContext.Setup(o => o.RequestServices.GetService(typeof(ITempDataDictionary))).Returns(tempData.Object);
            var actionContext = new ActionContext(httpContext.Object,
                                                  new RouteData(),
                                                  new ActionDescriptor());

            var result = new RedirectToRouteResult("SampleRoute", null)
            {
                UrlHelper = GetMockUrlHelper("SampleRoute")
            };

            // Act
            result.ExecuteResult(actionContext);

            // Assert
            tempData.Verify(t => t.Keep(), Times.Once());
        }
        public void WithController_GivenUnexpected_ShouldFail()
        {
            ActionResult result = new RedirectToRouteResult("", new RouteValueDictionary(
                new
                {
                    Controller = "home"
                }));

            Action a = () => result.Should()
                    .BeRedirectToRouteResult()
                    .WithController("xyz");
            a.ShouldThrow<Exception>()
                    .WithMessage("Expected dictionary to contain value \"xyz\" at key \"Controller\", but found \"home\".");
        }
Example #59
0
        public async Task ExecuteResultAsync_UsesRouteName_ToGenerateLocationHeader()
        {
            // Arrange
            var routeName = "orders_api";
            var locationUrl = "/api/orders/10";
            var urlHelper = new Mock<IUrlHelper>();
            urlHelper.Setup(uh => uh.RouteUrl(It.IsAny<UrlRouteContext>()))
                .Returns(locationUrl)
                .Verifiable();

            var serviceProvider = new Mock<IServiceProvider>();
            serviceProvider.Setup(sp => sp.GetService(typeof(IUrlHelper)))
                .Returns(urlHelper.Object);
            serviceProvider.Setup(sp => sp.GetService(typeof(ITempDataDictionary)))
                .Returns(new Mock<ITempDataDictionary>().Object);
            var httpContext = new DefaultHttpContext();
            httpContext.RequestServices = serviceProvider.Object;
            var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
            var result = new RedirectToRouteResult(routeName, new { id = 10 });

            // Act
            await result.ExecuteResultAsync(actionContext);

            // Assert
            urlHelper.Verify(uh => uh.RouteUrl(
                It.Is<UrlRouteContext>(routeContext => string.Equals(routeName, routeContext.RouteName))));
            Assert.True(httpContext.Response.Headers.ContainsKey("Location"), "Location header not found");
            Assert.Equal(locationUrl, httpContext.Response.Headers["Location"]);
        }
        public void WithArea_GivenExpected_ShouldPass()
        {
            ActionResult result = new RedirectToRouteResult("", new RouteValueDictionary(
                new
                {
                    Area = "accounts"
                }));

            result.Should()
                    .BeRedirectToRouteResult()
                    .WithArea("accounts");
        }