public async void RedirectToAction_Execute_PassesCorrectValuesToRedirect() { // 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 RedirectToActionResult("SampleAction", null, null) { 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 Execute(ActionContext context, RedirectToActionResult result) { var urlHelper = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context); var destinationUrl = urlHelper.Action(result.ActionName, result.ControllerName, result.RouteValues); if (string.IsNullOrEmpty(destinationUrl)) { throw new InvalidOperationException(Resources.NoRoutesMatched); } _logger.RedirectToActionResultExecuting(destinationUrl); context.HttpContext.Response.Redirect(destinationUrl, result.Permanent); }
public async void PostCreateParentBreedZero() { using (var database = new TestDb()) { var controller = new BreedsController(database.Context); IActionResult result = await controller.Create(new Breed { Name = "Test Breed with Zero Parent Breed", BreedId = 0 }); RedirectToActionResult redirect = Assert.IsType <RedirectToActionResult>(result); Assert.Equal("Index", redirect.ActionName); Breed breed = database.Context.Breeds.LastOrDefault(); Assert.Equal("Test Breed with Zero Parent Breed", breed.Name); } }
public void ShouldDeleteCorrectly() { Mock <IGenericService <LearningLine> > learningLineServiceMock = new Mock <IGenericService <LearningLine> >(); Mock <IObjectFinderService <Goal> > goalFinderMock = new Mock <IObjectFinderService <Goal> >(); Mock <IGenericService <Goal> > goalServiceMock = new Mock <IGenericService <Goal> >(); Mock <IManyToManyMapperService <LearningLine, LearningLineGoal, Goal> > mapperServiceMock = new Mock <IManyToManyMapperService <LearningLine, LearningLineGoal, Goal> >(); LearningLine learningLine = new LearningLine() { Id = 100, Name = "Computernetwerken" }; ClaimsPrincipal identity = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "123") })); goalFinderMock.Setup(m => m.GetObjects(It.IsAny <int[]>())).Returns((int[] ids) => { return(new List <Goal>()); }); learningLineServiceMock.Setup(m => m.FindById(It.IsAny <int>(), It.IsAny <string[]>())).Returns(learningLine); learningLineServiceMock.Setup(m => m.Delete(It.IsAny <LearningLine>())).Returns((LearningLine model) => { return(1); }); LearningLineController controller = new LearningLineController(learningLineServiceMock.Object, goalServiceMock.Object, goalFinderMock.Object, mapperServiceMock.Object) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = identity } } }; RedirectToActionResult result = controller.Delete(learningLine.Id) as RedirectToActionResult; Assert.Equal("Index", result?.ActionName); }
public async Task TestAdd() { this.ReferenceServices.CreateSectionType(Arg.Any <CreateSectionTypeDto>()).Returns(new SectionTypeDto { Id = 50 }); CreateSectionTypeViewModel lCreateSectionTypeViewModel = new CreateSectionTypeViewModel() { Name = "England" }; IActionResult lResult = await this.sectionTypeController.Add(lCreateSectionTypeViewModel); RedirectToActionResult lViewResult = lResult as RedirectToActionResult; Assert.AreEqual("SectionType successfully created", lViewResult.RouteValues["successMessage"]); await this.ReferenceServices.Received(1).CreateSectionType(Arg.Is <CreateSectionTypeDto>(dto => dto.Name == "England")); }
public void Can_Checkout_And_Submit_Order() { Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); Cart cart = new Cart(); cart.AddItem(new Product(), 1); OrderController target = new OrderController(mock.Object, cart); RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); Assert.Equal("Completed", result.ActionName); //Assert.False(string.IsNullOrEmpty(result.ViewName)); //Assert.True(result.ViewData.ModelState.IsValid); }
public void SearchTest() { // Arrange var BookServiceMoq = new Mock <IBookService>(); var AuthorServiceMoq = new Mock <IAuthorService>(); var RateServiceMoq = new Mock <IRateService>(); BookServiceMoq.Setup(service => service.GetAll()).Returns(_books.AsQueryable); AuthorServiceMoq.Setup(service => service.GetAll()).Returns(_authors.AsQueryable); RateServiceMoq.Setup(service => service.GetAll()).Returns(_rates.AsQueryable); HomeController controller = new HomeController(BookServiceMoq.Object, AuthorServiceMoq.Object, RateServiceMoq.Object); // Act RedirectToActionResult result = (RedirectToActionResult)controller.Index(); //Assert var viewResult = Assert.IsType <RedirectToActionResult>(result); }
public void Can_Checkout_And_Submit_Order() { // Arrange Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); // Arrange Cart cart = new Cart(); cart.Additem(new Product(), 1); // Arrange OrderController target = new OrderController(mock.Object, cart); // Act RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; // Assert Assert.Equal("Completed", result.ActionName); }
public void RedirectToActionResult_ThrowsEqualException_WhenRouteValuesNotEqual() { // Arrange var redirectToActionResult = new RedirectToActionResult("Index", "Home", new { ReturnUrl = "ReturnUrl" }); // Act & Assert Assert.Throws <EqualException>( () => MvcAssert.RedirectToActionResult( redirectToActionResult, "Index", "Home", new List <KeyValuePair <string, object> > { new KeyValuePair <string, object>("ReturnUrl", "NotReturnUrl") } ) ); }
public virtual async Task <IActionResult> Register(RegisterViewModel model) { RedirectToActionResult RedirectNextPage = RedirectToAction("Register", "Individual"); if (ModelState.IsValid) { model.UserRole = "Individual"; UserRegistrationResult Result = _userRegistrationService.RegisterUser(model); if (Result.Success) { await _signInManager.SignInAsync(Result.NewlyRegistredUser, isPersistent : false); RedirectNextPage = RedirectToUserPortalByRole(model.UserRole); } } return(RedirectNextPage); }
public void NewEntryTest() { MenuController controller = new MenuController(mockLogger.Object, mockService.Object) { TempData = tempData, }; // NewEntryメソッドのテスト IActionResult result = controller.NewEntry(); // 遷移先の確認 RedirectToActionResult actionResult = Assert.IsType <RedirectToActionResult>(result); Assert.Equal("index", actionResult.ActionName); Assert.Equal("Create", actionResult.ControllerName); controller.Dispose(); }
public async void PostEditWithParentBreedSuccess() { using (var database = new TestDb()) { var controller = new BreedsController(database.Context); IActionResult result = await controller.Edit(7, new Breed { Id = 7, Name = "Test Modified Breed with Parent Breed", BreedId = 2 }); RedirectToActionResult redirect = Assert.IsType <RedirectToActionResult>(result); Assert.Equal("Index", redirect.ActionName); Breed breed = database.Context.Breeds.SingleOrDefault(b => b.Name == "Test Modified Breed with Parent Breed"); Assert.Equal(7, breed.Id); Assert.Equal(2, breed.BreedId); } }
public async void PostCreateWithParentBreedSuccess() { using (var database = new TestDb()) { var controller = new BreedsController(database.Context); IActionResult result = await controller.Create(new Breed { Name = "Test Breed with Parent Breed", BreedId = 1 }); RedirectToActionResult redirect = Assert.IsType <RedirectToActionResult>(result); Assert.Equal("Index", redirect.ActionName); Breed breed = database.Context.Breeds.SingleOrDefault(b => b.Name == "Test Breed with Parent Breed"); Assert.Equal("Test Breed with Parent Breed", breed.Name); Assert.Equal(1, breed.ParentBreed.Id); } }
public void Can_Checkout_And_Submit_Order() { Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); Cart cart = new Cart(); cart.AddItem(new Product(), 1); OrderController target = new OrderController(cart, mock.Object); RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; // не вызывается(never) метод сохранить заказ mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); // возвращается стандарное представление Assert.Equal("Completed", result.ActionName); }
public void Can_Checkout_And_Submit_Order() { Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); Cart cart = new Cart(); cart.AddItem(new Product(), 1); OrderController target = new OrderController(mock.Object, cart); RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; // проверка сохранения mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); // проверка, что редирект сработал (на действие Completed в том же // классе-контроллере) Assert.Equal("Completed", result.ActionName); }
public void CanCheckoutAndSubmitOrder() { //Arrange Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); Cart cart = new Cart(); cart.AddItem(new Product(), 1); OrderController target = new OrderController(mock.Object, cart); //Act RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; //Assert mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); Assert.Equal("Completed", result.ActionName); }
public void Can_Checkout_And_Sumbit_Order() { //Организация - создание иммитированного хранилища заказов Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); //Организация - создание корзины с 1 элементом Cart cart = new Cart(); cart.AddItem(new Product(), 1); //Орзанизация - создание экзмепляра контроллера OrderController target = new OrderController(mock.Object, cart); //Действие - попытка перехода к оплате RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; //Утверждение - проверка, что заказ был сохранен mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); //Утверждение - проверка, что метод перенаправляется на действие Compiled Assert.Equal("Completed", result.ActionName); }
public void OnAuthorization(AuthorizationFilterContext context) { var authFailed = new RedirectToActionResult("Index", "Auth", null); if (!context.HttpContext.Request.Cookies.TryGetValue("token", out string token)) { context.Result = authFailed; } else { if (string.IsNullOrEmpty(token)) { context.Result = authFailed; } // verify token } }
public void Can_Checkout_And_Submit_Order() { //Arrange - create a mock order repository Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); //Arrange - create a cart with one item Cart cart = new Cart(); cart.AddItem(new Product(), 1); //Arrange - create an instance of the controller OrderController target = new OrderController(mock.Object, cart); //Act - try to checkout RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; //Assert - check that the order has been stored mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); //Assert - check that the method is redirecting to the completed action Assert.Equal("Completed", result.ActionName); }
public static IActionResult View(IActionResult value, params string[] RolList) { CurrentView = value; IActionResult view = null; try { if (LogUser == null || !LogUser.id.HasValue) { view = new RedirectResult("/Login"); } else if (SessionActiva()) { view = new RedirectResult("/Login/LockScreen"); } else { UserRoles = UserRoles ?? new List <Roles>(); if (RolList.Count() > 0) { if (UserRoles.Where(x => RolList.Contains(x.name)).Count() <= 0) { //view = new ViewResult() { ViewName = "Home", ViewData = new ViewDataDictionary() { { "error", "No tiene permisos suficientes" } } }; view = new RedirectToActionResult("Acceso", "Generales", new { Mensaje = "No tiene permisos suficientes" }); //throw new Exception("No tiene permisos suficientes"); } else { LastMove = DateTime.Now; } } } if (view == null) { view = value; } } catch (Exception e) { view = new RedirectToActionResult("Index", "Generales", new { Mensaje = e.Message }); } return(view); }
public async Task <IActionResult> Edit(string id, OfferEditBindingModel model) { if (id != model.Id) { return(NotFound()); } if (!ModelState.IsValid) { return(View(model)); } var offer = this.mapper.Map <OfferEditServiceModel>(model); var isOfferEdited = await this.offerServices.EditOfferAsync(offer); RedirectToActionResult redirectResult = new RedirectToActionResult("Edit", "Image", new { @Id = $"{id}" }); return(redirectResult); }
internal static RedirectToActionResult OnSignIn(ControllerBase controller, string authToken) { RedirectToActionResult redirectAction = null; string requestError = controller.Request.Form["error_description"]; if (!string.IsNullOrEmpty(requestError) && requestError.Contains(Constant.Message.UserPasswordForgotten)) { redirectAction = controller.RedirectToAction("passwordReset", "account"); } if (!string.IsNullOrEmpty(authToken)) { MediaClient.SetEventSubscription(authToken); using (MediaClient mediaClient = new MediaClient(authToken)) { mediaClient.CreateTransforms(); } } return(redirectAction); }
public void Can_Checkout_And_Submit_Order() { // Przygotowanie — tworzenie imitacji repozytorium. Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); // Przygotowanie — tworzenie koszyka z produktem. Cart cart = new Cart(); cart.AddItem(new Product(), 1); // Przygotowanie — tworzenie egzemplarza kontrolera. OrderController target = new OrderController(mock.Object, cart); // Działanie — próba zakończenia zamówienia. RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; // Asercje — sprawdzenie, czy zamówienie nie zostało przekazane do repozytorium. mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); // Asercje — sprawdzenie, czy metoda przekierowuje do metody akcji Completed(). Assert.Equal("Completed", result.ActionName); }
public void CreatePost_WithSuccessfullyCreatedTelescope_ShouldReturnRedirectResult() { // Arrange Mock <ITelescopeService> telescopeService = new Mock <ITelescopeService>(); const int telescopeId = 1; telescopeService .Setup(s => s.Exists(It.IsAny <string>())) .Returns(false); telescopeService .Setup(s => s.Create( It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <double>(), It.IsAny <string>())) .Returns(telescopeId); Mock <ITempDataDictionary> tempData = new Mock <ITempDataDictionary>(); string successmessage = null; tempData .SetupSet(t => t[WebConstants.TempDataSuccessMessage] = It.IsAny <string>()) .Callback((string key, object message) => successmessage = message as string); TelescopeFormServiceModel formModel = this.GetTelescopeFormModel(); TelescopesController telescopesController = new TelescopesController(telescopeService.Object); telescopesController.TempData = tempData.Object; // Act IActionResult result = telescopesController.Create(formModel); // Assert Assert.IsType <RedirectToActionResult>(result); RedirectToActionResult redirectResult = result as RedirectToActionResult; this.AssertRedirect(telescopeId, redirectResult); Assert.Equal(string.Format(WebConstants.SuccessfullEntityOperation, Telescope, WebConstants.Added), successmessage); }
public void OnAuthorization(AuthorizationFilterContext context) { var user = context.HttpContext.User; var isUserInRole = false; // Checking if user in role and Authorize permission foreach (var role in _roleList) { if (user.Identity.IsAuthenticated) { if (user.IsInRole(role) && _permission == AuthorizePermission.Allow) { isUserInRole = true; } if (!user.IsInRole(role) && _permission == AuthorizePermission.Disallow) { isUserInRole = true; } } } // Check if User is not authenticated and permission if (_roleList.Contains("Guest") && _permission == AuthorizePermission.Allow && !user.Identity.IsAuthenticated) { isUserInRole = true; } else if (_permission == AuthorizePermission.Disallow && !user.Identity.IsAuthenticated) { isUserInRole = true; } // Allow or disallow access source in order to below algorithm if (isUserInRole) { return; } var returnUrl = context.HttpContext.Request.Headers["Referer"].ToString(); var viewResult = new RedirectToActionResult("AccessDenied", "Account", new { returnUrl = returnUrl }); context.Result = viewResult; }
public void Can_Checkout_And_Submit_Order() { // Arrange - define imitation of the repository Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); // Arrange - define cart with the product Cart cart = new Cart(); cart.AddItem(new Product(), 1); // Arrange - creating a copy of the Controller OrderController target = new OrderController(mock.Object, cart); // Act - try end of the order RedirectToActionResult result = target.Checkout(new Order()) as RedirectToActionResult; // Assert - checking if order is not been placed in the repository mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); // Assert - checking if method redirects to the action method Completed() Assert.Equal("Completed", result.ActionName); }
public IActionResult UpdateProfile(UserDto dto) { string messages = ""; if (ModelState.IsValid) { ApiUpdate(dto); } else { var errors = ModelState.Where(x => x.Value.ValidationState == ModelValidationState.Invalid).SelectMany(x => x.Key + ": " + String.Join(", ", x.Value.Errors)); messages = String.Join("; ", errors); } // success or fail, we go back to the original page RedirectToActionResult redirectResult = new RedirectToActionResult("Profile", "Home", new { message = messages }); return(redirectResult); }
public void DeleteTruck_Ok() { var controller = new TruckController(repo); var truck = repo.List().FirstOrDefault(); TruckViewModel tvm = new TruckViewModel { Chassis = truck.Chassis, ModelYear = truck.ModelYear, BuildingYear = truck.BuildingYear }; var data = controller.Delete(tvm); RedirectToActionResult result = data as RedirectToActionResult; Assert.AreEqual("Index", result.ActionName); Assert.IsNull(repo.GetSingle(truck.Chassis)); }
public async Task Commit_WhenCalledWithInvalidDashboardSettingsViewModel_ReturnsRedirectToActionResult() { OSDevGrp.MyDashboard.Web.Controllers.HomeController sut = CreateSut(false); DashboardSettingsViewModel dashboardSettingsViewModel = BuildDashboardSettingsViewModel(_random); IActionResult result = await sut.Commit(dashboardSettingsViewModel); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(RedirectToActionResult)); RedirectToActionResult redirectToActionResult = (RedirectToActionResult)result; Assert.IsNotNull(redirectToActionResult); Assert.IsNotNull(redirectToActionResult.ActionName); Assert.AreEqual("Index", redirectToActionResult.ActionName); Assert.IsNotNull(redirectToActionResult.ControllerName); Assert.AreEqual("HomeController", redirectToActionResult.ControllerName); }
public void Can_Checkout_And_Submit_Order() { //Assign - create imitation of the repository Mock <IOrderRepository> mock = new Mock <IOrderRepository>(); //Assign - create cart with a product Cart cart = new Cart(); cart.AddItem(new Product(), 1); //Assign - create controller OrderController target = new OrderController(mock.Object, cart); //Act - attemp to finish an order RedirectToActionResult result = target.CheckOut(new Order()) as RedirectToActionResult; //Assert - check if an order wasn't handed to the repository mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once); //???? Once? //Assert - check if a method redirects to an action method Colpeted() Assert.Equal("Completed", result.ActionName); }
public void Register_Successfully() { _accountLogic.Setup(x => x.EncryptPassword(It.IsAny <string>())).Returns("parolaencryptata").Verifiable(); _accountControllerHelper.Setup(x => x.BuildDTO(It.IsAny <RegisterViewModel>())).Returns(new CinemaUserDTO()).Verifiable(); _userLogic.Setup(x => x.AddUser(It.IsAny <CinemaUserDTO>(), It.IsAny <string>())).Returns(new Response { IsCompletedSuccesfuly = true }).Verifiable(); RedirectToActionResult result = _accountController.Register(new RegisterViewModel { Password = "******", RePassword = "******" }) as RedirectToActionResult; Assert.That(result.ControllerName, Is.EqualTo("Home")); Assert.That(result.ActionName, Is.EqualTo("Index")); _accountLogic.Verify(x => x.EncryptPassword(It.IsAny <string>()), Times.Exactly(2)); _accountControllerHelper.Verify(x => x.BuildDTO(It.IsAny <RegisterViewModel>()), Times.Exactly(1)); _userLogic.Verify(x => x.AddUser(It.IsAny <CinemaUserDTO>(), It.IsAny <string>()), Times.Exactly(1)); }
public async Task UpdateUserOptionsPost_ResetUserOptions_ReturnsARedirectResult() { //Arrange System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Mock <ISilveRRepository> mock = new Mock <ISilveRRepository>(); mock.Setup(x => x.GetUserOptions()).ReturnsAsync(It.IsAny <UserOption>()); UserOptionsController sut = new UserOptionsController(mock.Object); //Act IActionResult result = await sut.UpdateUserOptions(new UserOption(), "reset"); //Assert RedirectToActionResult viewResult = Assert.IsType <RedirectToActionResult>(result); //Assert.Equal("UserOptions", viewResult.ControllerName);? Assert.Equal("Index", viewResult.ActionName); }
public void RedirectToAction_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); RedirectToActionResult result = new RedirectToActionResult(urlHelper, null, null, null); // Act & Assert ExceptionAssert.ThrowsAsync<InvalidOperationException>( async () => { await result.ExecuteResultAsync(actionContext); }, "No route matches the supplied values."); }
public void RedirectToAction_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 RedirectToActionResult("SampleAction", null, null) { UrlHelper = GetMockUrlHelper("SampleAction") }; // Act result.ExecuteResult(actionContext); // Assert tempData.Verify(t => t.Keep(), Times.Once()); }