public void FindView_UsesViewEngine_FromViewResult() { // Arrange var context = GetActionContext(); var executor = GetViewExecutor(); var viewName = "my-view"; var viewEngine = new Mock<ICompositeViewEngine>(MockBehavior.Strict); viewEngine .Setup(e => e.GetView(/*executingFilePath*/ null, viewName, /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound(viewName, Enumerable.Empty<string>())) .Verifiable(); viewEngine .Setup(e => e.FindView(context, viewName, /*isMainPage*/ true)) .Returns(ViewEngineResult.Found(viewName, Mock.Of<IView>())) .Verifiable(); var viewResult = new ViewResult { ViewEngine = viewEngine.Object, ViewName = viewName, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act var viewEngineResult = executor.FindView(context, viewResult); // Assert Assert.Equal(viewName, viewEngineResult.ViewName); viewEngine.Verify(); }
public AutoMapViewResult(IMapper mapper, Type sourceType, Type destinationType, ViewResult view) { Mapper = mapper; SourceType = sourceType; DestinationType = destinationType; View = view; }
public void FindView_UsesViewEngine_FromViewResult() { // Arrange var context = GetActionContext(); var executor = GetViewExecutor(); var viewName = "my-view"; var viewEngine = new Mock<ICompositeViewEngine>(); viewEngine .Setup(e => e.FindView(context, viewName)) .Returns(ViewEngineResult.Found(viewName, Mock.Of<IView>())) .Verifiable(); var viewResult = new ViewResult { ViewEngine = viewEngine.Object, ViewName = viewName, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act var viewEngineResult = executor.FindView(context, viewResult); // Assert Assert.Equal(viewName, viewEngineResult.ViewName); viewEngine.Verify(); }
public async Task ExecuteResultAsync_Throws_IfViewCouldNotBeFound_MessageUsesGetViewLocations() { // Arrange var expected = string.Join( Environment.NewLine, "The view 'MyView' was not found. The following locations were searched:", "Location1", "Location2"); var actionContext = GetActionContext(); var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); viewEngine .Setup(e => e.GetView(/*executingFilePath*/ null, "MyView", /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound("MyView", new[] { "Location1", "Location2" })) .Verifiable(); viewEngine .Setup(v => v.FindView(It.IsAny<ActionContext>(), It.IsAny<string>(), /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound("MyView", Enumerable.Empty<string>())) .Verifiable(); var viewResult = new ViewResult { ViewEngine = viewEngine.Object, ViewName = "MyView", ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act and Assert var ex = await Assert.ThrowsAsync<InvalidOperationException>( () => viewResult.ExecuteResultAsync(actionContext)); Assert.Equal(expected, ex.Message); viewEngine.Verify(); }
private string RenderHtml(IComponent component) { if (string.IsNullOrEmpty(ViewHtml)) { ViewHtml = new ViewResult(layOutViewName, new PageModel() { ActiveMenuIndex = 0, IsLogin = true }).Execute(); } return ViewHtml; }
public void Model_NullWhenViewDataIsNull() { // Arrange var viewResult = new ViewResult(); // Act & Assert Assert.Null(viewResult.Model); }
/// <summary> /// Attempts to find the <see cref="IView"/> associated with <paramref name="viewResult"/>. /// </summary> /// <param name="actionContext">The <see cref="ActionContext"/> associated with the current request.</param> /// <param name="viewResult">The <see cref="ViewResult"/>.</param> /// <returns>A <see cref="ViewEngineResult"/>.</returns> public virtual ViewEngineResult FindView(ActionContext actionContext, ViewResult viewResult) { if (actionContext == null) { throw new ArgumentNullException(nameof(actionContext)); } if (viewResult == null) { throw new ArgumentNullException(nameof(viewResult)); } var viewEngine = viewResult.ViewEngine ?? ViewEngine; var viewName = viewResult.ViewName ?? actionContext.ActionDescriptor.Name; var result = viewEngine.FindView(actionContext, viewName); if (result.Success) { if (DiagnosticSource.IsEnabled("Microsoft.AspNet.Mvc.ViewFound")) { DiagnosticSource.Write( "Microsoft.AspNet.Mvc.ViewFound", new { actionContext = actionContext, isPartial = false, result = viewResult, viewName = viewName, view = result.View, }); } Logger.LogVerbose("The view '{ViewName}' was found.", viewName); } else { if (DiagnosticSource.IsEnabled("Microsoft.AspNet.Mvc.ViewNotFound")) { DiagnosticSource.Write( "Microsoft.AspNet.Mvc.ViewNotFound", new { actionContext = actionContext, isPartial = false, result = viewResult, viewName = viewName, searchedLocations = result.SearchedLocations }); } Logger.LogError( "The view '{ViewName}' was not found. Searched locations: {SearchedViewLocations}", viewName, result.SearchedLocations); } return result; }
public void ReturnsTrueWhenViewResultHasRows() { var viewResult = new ViewResult<TestDocument>(); var viewRow = new ViewResultRow<TestDocument>(); var viewResultRows = new List<ViewResultRow<TestDocument>> {viewRow}; viewResult.Rows = viewResultRows.ToArray(); Assert.That(viewResult.HasRows(), Is.True); }
public void ConstructorThrowsIfControllerContextIsNull() { // Arrange ControllerContext controllerContext = null; ActionResult result = new ViewResult(); // Act & assert Assert.ThrowsArgumentNull( delegate { new ResultExecutingContext(controllerContext, result); }, "controllerContext"); }
public void ConstructorThrowsIfControllerDescriptorIsNull() { // Arrange ControllerContext controllerContext = null; ActionResult result = new ViewResult(); bool canceled = true; Exception exception = null; // Act & assert Assert.ThrowsArgumentNull( delegate { new ResultExecutedContext(controllerContext, result, canceled, exception); }, "controllerContext"); }
public void ResultProperty() { // Arrange ControllerContext controllerContext = new Mock<ControllerContext>().Object; ActionResult result = new ViewResult(); // Act ResultExecutingContext resultExecutingContext = new ResultExecutingContext(controllerContext, result); // Assert Assert.Equal(result, resultExecutingContext.Result); }
public override void OnException(ExceptionContext context) { if (!_hostingEnvironment.IsDevelopment()) { // do nothing return; } var result = new ViewResult {ViewName = "CustomError"}; result.ViewData = new ViewDataDictionary(_modelMetadataProvider,context.ModelState); result.ViewData.Add("Exception", context.Exception); // TODO: Pass additional detailed data via ViewData context.ExceptionHandled = true; // mark exception as handled context.Result = result; }
private string RenderHtml(IComponent component) { if (string.IsNullOrEmpty(ViewHtml)) { UserInfo user = Authorization.Instance.CurrentUser(); string userid = string.Empty; if (user != null) { userid = user.UserID; } ViewHtml = new ViewResult(layOutViewName, new PageModel() { ActiveMenuIndex = 0, DisplayName = userid, IsLogin = true }).Execute(); } return ViewHtml; }
public async Task ExecuteResultAsync_WritesOutputWithoutBOM() { // Arrange var expected = new byte[] { 97, 98, 99, 100 }; var view = new Mock<IView>(); view.Setup(v => v.RenderAsync(It.IsAny<ViewContext>())) .Callback((ViewContext v) => { view.ToString(); v.Writer.Write("abcd"); }) .Returns(Task.FromResult(0)); var routeDictionary = new Dictionary<string, object>(); var viewEngine = new Mock<ICompositeViewEngine>(); var serviceProvider = new Mock<IServiceProvider>(); serviceProvider.Setup(sp => sp.GetService(typeof(ICompositeViewEngine))) .Returns(viewEngine.Object); var memoryStream = new MemoryStream(); var response = new Mock<HttpResponse>(); response.SetupGet(r => r.Body) .Returns(memoryStream); var context = new Mock<HttpContext>(); context.SetupGet(c => c.Response) .Returns(response.Object); context.SetupGet(c => c.RequestServices) .Returns(serviceProvider.Object); var actionContext = new ActionContext(context.Object, new RouteData() { Values = routeDictionary }, new ActionDescriptor()); viewEngine.Setup(v => v.FindView(actionContext, It.IsAny<string>())) .Returns(ViewEngineResult.Found("MyView", view.Object)); var viewResult = new ViewResult(); // Act await viewResult.ExecuteResultAsync(actionContext); // Assert Assert.Equal(expected, memoryStream.ToArray()); }
public void Model_ExposesViewDataModel() { // Arrange var customModel = new object(); var viewResult = new ViewResult { ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()) { Model = customModel }, }; // Act & Assert Assert.Same(customModel, viewResult.Model); }
private string RenderHtml(IConfigBean component, IPayLoad context) { if (string.IsNullOrEmpty(ViewHtml)) { UserInfo user = Authorization.Instance.CurrentUser(); string userid = string.Empty; if (user != null) { userid = user.UserID; } ViewHtml = new ViewResult(layOutViewName, new PageModel() { ActiveMenuIndex = 2, DisplayName = userid, IsLogin = true }).Execute(); ViewHtml = ViewHtml.Replace("@ComponentBody@", BuildContent(context)); } return ViewHtml; }
public void PropertiesAreSetByConstructor() { // Arrange ControllerContext controllerContext = new Mock<ControllerContext>().Object; ActionResult result = new ViewResult(); bool canceled = true; Exception exception = new Exception(); // Act ResultExecutedContext resultExecutedContext = new ResultExecutedContext(controllerContext, result, canceled, exception); // Assert Assert.Equal(result, resultExecutedContext.Result); Assert.Equal(canceled, resultExecutedContext.Canceled); Assert.Equal(exception, resultExecutedContext.Exception); }
public void ExecuteWritesViewToStream() { // Given var view = A.Fake<IView>(); A.CallTo(() => view.Execute()).Invokes(x => view.Writer.Write("Test")); var result = new ViewResult(view, "location"); var stream = new MemoryStream(); // When result.Execute(stream); // Then stream.Position = 0; using (var reader = new StreamReader(stream)) { reader.ReadToEnd().ShouldEqual("Test"); } }
public void GetDocumentByKeyFromViewByCallingGetJsonForView() { var viewresult = new ViewResult<TestDocument> { RowCount = 1, Rows = new[]{new ViewResultRow<TestDocument> {Id = "1", Key = "1", Value = new TestDocument("1")}} }; var expectedJson = viewresult.Serialize(); mockCouchUriBuilder.Setup(s => s.ForView(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())).Returns(documentUri); mockJsonClient.Setup(c => c.GetJsonFrom(documentUri)).Returns(expectedJson); var testDocument = viewRepository.GetDocument("designdoc", "viewname", "1"); mockCouchUriBuilder.Verify(s => s.ForView("designdoc", "viewname", "1")); mockJsonClient.Verify(c => c.GetJsonFrom(documentUri)); Assert.That((object) testDocument.Id, Is.EqualTo("1")); }
public void OnAuthorizationDoesNothingIfRequestIsSecure() { // Arrange Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>(); mockAuthContext.Setup(c => c.HttpContext.Request.IsSecureConnection).Returns(true); AuthorizationContext authContext = mockAuthContext.Object; ViewResult result = new ViewResult(); authContext.Result = result; RequireHttpsAttribute attr = new RequireHttpsAttribute(); // Act attr.OnAuthorization(authContext); // Assert Assert.Same(result, authContext.Result); }
public void Cannot_Checkout_Invalid_ShippingDetails() { Mock <IOrderProcessor> mock = new Mock <IOrderProcessor>(); Cart cart = new Cart(); cart.AddItem(new Product(), 1); CartController controller = new CartController(null, mock.Object); controller.ModelState.AddModelError("error", "error"); ViewResult result = controller.Checkout(cart, new ShippingDetails()); mock.Verify(m => m.ProcessOrder(It.IsAny <Cart>(), It.IsAny <ShippingDetails>()), Times.Never()); Assert.AreEqual("", result.ViewName); Assert.AreEqual(false, result.ViewData.ModelState.IsValid); }
public void Index_ShouldReturnNonNullResult() { // Arrange Mapper.Initialize(cfg => { cfg.CreateMap <Course, CourseTileViewModel>(); cfg.CreateMap <CourseTileViewModel, Course>(); }); var courseServiceStub = new Mock <ICourseService>(); var mapperStub = new Mock <IMapper>(); HomeController controller = new HomeController(courseServiceStub.Object, mapperStub.Object); // Act ViewResult result = controller.Index() as ViewResult; // Assert Assert.IsNotNull(result); }
public void FindView_UsesActionDescriptorName_IfViewNameIsNull() { // Arrange var viewName = "some-view-name"; var context = GetActionContext(viewName); var executor = GetViewExecutor(); var viewResult = new ViewResult { ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act var viewEngineResult = executor.FindView(context, viewResult); // Assert Assert.Equal(viewName, viewEngineResult.ViewName); }
public async Task <IActionResult> Make(ReplyInputModel model) { if (this.ModelState.IsValid) { GamingForumUser replier = await this.accountService.GetLoggedInUserAsync(this.User); await this.replyService.MakeAsync(model, replier); return(this.Redirect($"/Post/Details/{model.PostId}")); } else { ViewResult result = this.View("Error", this.ModelState); result.StatusCode = (int)HttpStatusCode.BadRequest; return(result); } }
public async Task Edit_Post_UserFoundAndIdentityResultNotSucceeded_AsksForEditView() { Mock <IUserStore <AppUser> > userStore = new Mock <IUserStore <AppUser> >(); Mock <AppUserManager> userManager = new Mock <AppUserManager>(userStore.Object); userManager.Setup(m => m.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(new AppUser { }); Mock <UserValidator <AppUser> > userValidator = new Mock <UserValidator <AppUser> >(); userValidator.Setup(m => m.ValidateAsync(It.IsAny <AppUser>())).ReturnsAsync(IdentityResult.Success); userManager.Setup(m => m.UpdateAsync(It.IsAny <AppUser>())).ReturnsAsync(IdentityResult.Success); AdminController controller = GetNewAdminController(userManager.Object); ViewResult result = (await controller.Edit(new EditModel { Password = "" })) as ViewResult; Assert.AreEqual("Edit", result.ViewName); }
public ActionResult Random() { var movie = new Movie() { Name = "Shrek!" }; var viewResult = new ViewResult(); var customers = new List<Customer> { new Customer {Name = "Customer 1 "}, new Customer {Name = "Customer 2 "} }; var viewModel = new RandomMovieViewModel { Movie = movie, Customers = customers }; return View(viewModel); }
private void ProcessException(ExceptionContext context, ITempDataDictionary tempData) { if (!(context.ActionDescriptor is ControllerActionDescriptor)) return; const string errorViewName = "Error"; var result = new ViewResult { ViewName = errorViewName, TempData = tempData, ViewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState) { {"Notifications", tempData[NotificationHelper.NotificationKey]}, } }; context.ExceptionHandled = true; context.Result = result; }
public void Login() { // Arrange Mock <ISecurityAdapter> mockSecurityAdapter = new Mock <ISecurityAdapter>(); string returnUrl = "/testreturnurl"; // Act AccountController controller = new AccountController(mockSecurityAdapter.Object); ActionResult result = controller.Login(returnUrl); // Assert Assert.True(result is ViewResult); ViewResult viewResult = result as ViewResult; Assert.True(viewResult.Model is AccountLoginModel); AccountLoginModel model = viewResult.Model as AccountLoginModel; Assert.True(model.ReturnUrl == returnUrl); }
public JToken[] GetDocuments(string[] ids) { if (ids == null) { throw new System.ArgumentNullException("ids"); } if (ids.Length == 0) { return(new JToken[0]); } var keys = new Keys(); keys.Values.AddRange(ids); ViewResult viewResult = couchDB.GetDocuments(keys); return(viewResult.Rows.ToArray()); }
public void Index_ViewModel_ShouldHaveExactlyThreeUpcomingCourses() { // Arrange var listOfCourses = new List <Course>() { new Course() { StartsOn = new DateTime(5540, 2, 2) }, new Course() { StartsOn = new DateTime(5540, 2, 2) }, new Course() { StartsOn = new DateTime(5540, 2, 2) }, new Course() { StartsOn = new DateTime(5540, 2, 2) } }; var courseServiceStub = new Mock <ICourseService>(); courseServiceStub.Setup(cs => cs.GetAll()).Returns(listOfCourses.AsQueryable()); var mapperStub = new Mock <IMapper>(); Mapper.Initialize(cfg => { cfg.CreateMap <Course, CourseTileViewModel>(); cfg.CreateMap <CourseTileViewModel, Course>(); }); HomeController controller = new HomeController(courseServiceStub.Object, mapperStub.Object); // Act ViewResult result = controller.Index() as ViewResult; // Assert Assert.AreEqual(3, ((HomeViewModel)result.ViewData.Model).Courses.Count()); }
public void AllCourses_ShouldReturnNonNullResult() { // Arrange Mapper.Initialize(cfg => { cfg.CreateMap <Course, CourseViewModel>(); cfg.CreateMap <CourseViewModel, Course>(); }); var courseServiceStub = new Mock <ICourseService>(); var userServiceStub = new Mock <IUserService>(); CoursesController controller = new CoursesController(courseServiceStub.Object, userServiceStub.Object); // Act ViewResult result = controller.AllCourses() as ViewResult; // Assert Assert.IsNotNull(result); }
public void ResendConfirmation_POST_With_Invalid_Email_Should_Show_Signup_View() { // Arrange _applicationSettings.UseWindowsAuthentication = false; SiteSettings siteSettings = _settingsService.GetSiteSettings(); ResetPasswordEmailStub resetEmail = new ResetPasswordEmailStub(_applicationSettings, _repository, _emailClientMock); UserController userController = new UserController(_applicationSettings, _userService, _userContext, _settingsService, null, resetEmail); userController.SetFakeControllerContext(); // Act ActionResult result = userController.ResendConfirmation("doesnt exist"); // Assert ViewResult viewResult = result.AssertResultIs <ViewResult>(); Assert.That(viewResult.ViewName, Is.EqualTo("Signup")); }
/// <summary> /// 各Actionメソッドから例外がthrowされた際に呼び出される。 /// </summary> /// <param name="context"></param> public void OnException(ExceptionContext context) { if (context.ExceptionHandled) { return; //他の例外で処理済なら何もしない。 } context.ExceptionHandled = true; Exception ex = context.Exception; logger.Error("エラーが発生しました。", LogType.Exception, ex: ex); string message = (ex as CustomException)?.Message ?? "エラーが発生しました。"; _ = sendGridHelper.SendMessage("【執務管理システム】 エラーが発生しました。", ex.ToString()); //Ajaxもしくはformアプリからのリクエストの場合はJsonを返す。 if (context.HttpContext.Request.IsApiOrAjaxRequest()) { //Ajaxリクエストに対するresult。 context.Result = WebUtil.JsonString(RequestResult.CreateErrorResult(message)); } else if (StreamRequestAttribute.IsStreamFileRequest((context.ActionDescriptor as ControllerActionDescriptor)?.MethodInfo)) { //Streamリクエストに対するresult。 //とりあえずJsonと一緒。 context.Result = WebUtil.JsonContent(RequestResult.CreateErrorResult(message)); } else { ViewResult errorPageResult = new ViewResult() { ViewName = ErrorViewName, //デフォルトでViews\SharedのError.cshtmlが呼ばれる。 TempData = tempDataDictionaryFactory.GetTempData(context.HttpContext) }; if (!string.IsNullOrEmpty(message)) { errorPageResult.ViewData = new ViewDataDictionary(modelMetadataProvider, context.ModelState); errorPageResult.ViewData["ERROR_KEY"] = message; } context.Result = errorPageResult; } }
public void GetDifferenceWithValidDates() { // Arrange DateDiffController controller = new DateDiffController(); DateViewModel model = new DateViewModel() { FromDate = "02/02/2018", ToDate = "04/02/2018" }; // Act ViewResult result = controller.OnSubmit(model) as ViewResult; // Assert Assert.IsNotNull(result); var resultModel = result.Model as DateViewModel; Assert.AreEqual(resultModel.TotalDays, 2); }
public void EditInvalidAthlete() { //arrange controller.ModelState.AddModelError("key", "error message"); Athlete athlete = new Athlete { Pk_Athlete_Id = 4, Fk_Sport_Id = 4, FullName = "john", Email = "*****@*****.**", MobileNo = "519-803-2269" }; //Act - cast return type as ViewResult ViewResult actual = (ViewResult)controller.Edit(athlete); //Assert Assert.AreEqual("Edit", actual.ViewName); }
public override StringBuilder Render(ViewResult viewResult, ViewRenderingContext context) { var view = this.GetViewInstance(viewResult, context); view.ExecuteView(null, null); var body = view.Body; var sectionContents = view.SectionContents; // null means no override, string.Empty means ensure there is no layout if (viewResult.MasterPageOverride != null) { view.Layout = viewResult.MasterPageOverride; } var root = string.IsNullOrWhiteSpace(view.Layout); // render the initial view, and move "up" through its parent layouts while (!root) { Type masterType; try { masterType = this.viewResolver.Resolve(view.Layout); } catch (Exception ex) { throw new Exception($"Unable to resolve layout for view: {view}", ex); } var masterResult = new ViewResult(masterType, viewResult.AreaName, viewResult.ViewData, viewResult.StatusCode); view = this.GetViewInstance(masterResult, context); view.ExecuteView(body, sectionContents); body = view.Body; sectionContents = view.SectionContents; root = !view.HasLayout; } return(new StringBuilder(body)); }
void IsUserAuthorized(AuthorizationContext filterContext) { if (filterContext.Result == null) { return; } if (filterContext.HttpContext.User.Identity.IsAuthenticated) { ViewDataDictionary dic = new ViewDataDictionary(); dic.Add("Message", "Your account cannot access this page, please Log -in an Administrator Account. " + "For more information, contact Sonic IT Support: "); var results = new ViewResult() { ViewName = this.ViewName, ViewData = dic }; filterContext.Result = results; } }
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext) { if (filterContext.HttpContext.Request.IsAuthenticated) { var viewResult = new ViewResult { ViewName = "~/Views/Account/Unauthorized.cshtml" }; filterContext.Result = viewResult; } else { var viewResult = new ViewResult { ViewName = "~/Views/Account/Login.cshtml" }; filterContext.Result = viewResult; } }
public void ReservationController_ConfirmationAction_ReturnConfirmationView() { //Arrange ReservationController controller = new ReservationController(); Reservation reservation = new Reservation() { SiteID = 1, ReservationStart = DateTime.Today, ReservationEnd = DateTime.Today, ReservationName = "Test" }; //Act ViewResult result = controller.Confirmation(reservation) as ViewResult; //Assert Assert.IsNotNull(result); Assert.AreEqual("Confirmation", result.ViewName); }
public void EditAction_Saves_Changes_To_Dinner_1() { // Arrange var repo = new FakeDinnerRepository(FakeDinnerData.CreateTestDinners()); var controller = CreateDinnersControllerAs("SomeUser"); var form = FakeDinnerData.CreateDinnerFormCollection(); form["Description"] = "New, Updated Description"; controller.ValueProvider = form.ToValueProvider(); // Act ActionResult result = (ActionResult)controller.Edit(1, form); ViewResult detailResult = (ViewResult)controller.Details(1); var dinner = detailResult.ViewData.Model as Dinner; // Assert Assert.AreEqual(5, controller.ModelState.Count); Assert.AreEqual("New, Updated Description", dinner.Description); }
protected override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); // handling exceptions related to network/communication // with github api directly at controller level and notifying user. // additionally we can log this exception to file or database logging using nlog. filterContext.ExceptionHandled = true; // redirecting to index view with error information var viewResult = new ViewResult { ViewName = "Index" }; viewResult.ViewBag.ErrorMessage = string.Format("Something went wrong. Please try again! Technical Details: {0}", filterContext.Exception.ToString()); filterContext.Result = viewResult; }
public void Index_IsAuthenticated() { // user authenticated // arrange HomeController controller = new HomeController(fUow); // fake authentication = true controller.ControllerContext = FakeUserAuthContext.UserAuthenticated(true, controller); // act ViewResult viewResult = (ViewResult)controller.Index(); // assert var model = viewResult.Model as BookListingViewModel; Assert.AreEqual(1, (model.ExpiredBorrowing.Count)); Assert.AreEqual(3, (model.ValidBorrowing.Count)); }
public async Task <IActionResult> Create(PostInputModel model) { if (this.ModelState.IsValid) { GamingForumUser poster = await this.accountService.GetLoggedInUserAsync(this.User); await this.postService.CreateAsync(model, poster); return(this.Redirect($"/Category/Details/{model.CategoryId}")); } else { ViewResult result = this.View("Error", this.ModelState); result.StatusCode = (int)HttpStatusCode.BadRequest; return(result); } }
public void WithViewData_GivenUnexpectedValue_ShouldFail() { var key = "key1"; var actualValue = "value1"; var expectedValue = "abc"; var failureMessage = FailureMessageHelper.Format(FailureMessages.ViewResultBase_ViewData_HaveValue, key, expectedValue, actualValue); ActionResult result = new ViewResult { ViewData = new ViewDataDictionary { { key, actualValue } } }; Action a = () => result.Should().BeViewResult().WithViewData(key, expectedValue); a.Should().Throw <Exception>() .WithMessage(failureMessage); }
public void GetDeliveriesList_ReturnsCorrectViewResult() { // Arrange Mock <IDeliveryProvider> deliveryProviderMock = new Mock <IDeliveryProvider>(); deliveryProviderMock.Setup(x => x.GetAll()) .Returns(deliveries); Mock <IDeliveryHandler> deliveryHandlerMock = new Mock <IDeliveryHandler>(); Mock <IDeliveryValidator> deliveryValidatorMock = new Mock <IDeliveryValidator>(); DeliveryController controller = new DeliveryController(deliveryProviderMock.Object, deliveryHandlerMock.Object, deliveryValidatorMock.Object); // Act ViewResult result = controller.GetDeliveriesList() as ViewResult; // Assert Assert.IsNotNull(result); Assert.IsTrue(((List <Delivery>)result.Model).Count == 2); Assert.AreEqual("GetDeliveriesList", result.ViewName); }
public void RequireHttpsAttributeDoesNotThrowForSecureConnection() { // Arrange var mockAuthContext = new Mock <AuthorizationContext>(MockBehavior.Strict); mockAuthContext.SetupGet(c => c.HttpContext.Request.IsLocal).Returns(false); mockAuthContext.SetupGet(c => c.HttpContext.Request.IsSecureConnection).Returns(true); var context = mockAuthContext.Object; var attribute = new RequireRemoteHttpsAttribute(); var result = new ViewResult(); context.Result = result; // Act attribute.OnAuthorization(context); // Assert Assert.Same(result, context.Result); }
public void GetDelivery_ReturnsCorrectViewResult() { // Arrange Mock <IDeliveryProvider> deliveryProviderMock = new Mock <IDeliveryProvider>(); deliveryProviderMock.Setup(x => x.GetById(1)) .Returns(deliveries[0]); Mock <IDeliveryHandler> deliveryHandlerMock = new Mock <IDeliveryHandler>(); Mock <IDeliveryValidator> deliveryValidatorMock = new Mock <IDeliveryValidator>(); DeliveryController controller = new DeliveryController(deliveryProviderMock.Object, deliveryHandlerMock.Object, deliveryValidatorMock.Object); // Act ViewResult result = controller.GetDelivery(1) as ViewResult; // Assert Assert.IsNotNull(result); Assert.IsTrue(((Delivery)result.Model).Id != default(int)); Assert.AreEqual("GetDelivery", result.ViewName); }
public void CannotEditWithMissingValues() { Mock <IGenericService <Goal> > goalServiceMock = new Mock <IGenericService <Goal> >(); Goal goal = new Goal() { Id = 100, Bloom = null, Description = @"Je begrijpt de basismechanismen voor access control, zodanig dat je in eigen woorden kunt uitleggen wat de betekenis is in de context van software security. " }; ClaimsPrincipal identity = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "123") })); goalServiceMock.Setup(m => m.Update(It.IsAny <Goal>())).Returns((Goal model) => { if (!string.IsNullOrWhiteSpace(model.Bloom) && !string.IsNullOrWhiteSpace(model.Description)) { return(1); } return(0); }); GoalController controller = new GoalController(goalServiceMock.Object) { ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = identity } } }; ViewResult result = controller.Edit(goal) as ViewResult; Assert.NotNull(result); Assert.NotNull(result.Model); Assert.True(string.IsNullOrEmpty(result.ViewName) || result.ViewName == "Edit"); }
public void Should_Return_View_Results_With_Documents() { CouchDatabase db = client.GetDatabase(baseDatabase); db.CreateDocument(new JDocument()); db.CreateDocument(new JDocument()); db.CreateDocument(new JDocument()); ViewResult <string, JObject, JDocument> result = db.GetView <string, JObject, JDocument>("testviewitem", "testview"); Assert.IsNotNull(result); foreach (ViewResultRow <string, JObject, JDocument> row in result.Rows) { Assert.IsNotNull(row.Doc); Assert.IsNotNull(row.Key); Assert.IsNotNull(row.Id); Assert.IsNotNull(row.Value); } }
public void Books_Details() { // Arrange Source source = GetTestSource(); var books = GetTestBookSet(source); var db = new Mock <IPersonalInformationManagerContext>(); db.Setup(e => e.Books).Returns(books); db.Setup(e => e.Books.Find(It.IsAny <int>())).Returns(GetTestBook(source)); BooksController controller = new BooksController(db.Object); // Act ViewResult result = controller.Details(1) as ViewResult; var model = result.Model as PersonalInformationManager.Models.Book; // Assert Assert.IsNotNull(result); Assert.AreEqual(BOOK_TITLE, model.Title); }
public void CannotUpdateInvalidAssetContentFromForm() { // Establish Context AssetContent assetContentFromForm = new AssetContent(); AssetContentFormViewModel viewModelToExpect = new AssetContentFormViewModel(); assetContentManagementService.Expect(r => r.UpdateWith(assetContentFromForm, 0)) .Return(ActionConfirmation.CreateFailureConfirmation("not updated")); assetContentManagementService.Expect(r => r.CreateFormViewModelFor(assetContentFromForm)) .Return(viewModelToExpect); // Act ViewResult result = assetContentsController.Edit(assetContentFromForm).AssertViewRendered(); // Assert result.ViewData.Model.ShouldNotBeNull(); (result.ViewData.Model as AssetContentFormViewModel).ShouldNotBeNull(); }
public void OnException(ExceptionContext context) { //if (!_hostingEnvironment.IsDevelopment()) //{ // // do nothing // return; //} var model = new ErrorPageViewModel { ErrorMessage = context.Exception.Message }; var viewData = new ViewDataDictionary(_modelMetadataProvider, context.ModelState); var result = new ViewResult { ViewName = "ErrorFilter", ViewData = new ViewDataDictionary<ErrorPageViewModel>(viewData, model) }; context.ExceptionHandled = true; // mark exception as handled context.Result = result; }
public void BeginInvokeActionMethodWithFilters_ShortCircuited() { // Arrange List<string> actionLog = new List<string>(); ActionResult shortCircuitResult = new ViewResult(); ActionResult executeResult = new ViewResult(); ActionFilterImpl filter1 = new ActionFilterImpl() { OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add("OnActionExecuting1"); }, OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add("OnActionExecuted1"); } }; ActionFilterImpl filter2 = new ActionFilterImpl() { OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add("OnActionExecuting2"); filterContext.Result = shortCircuitResult; }, OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add("OnActionExecuted2"); } }; Func<ActionResult> endExecute = () => { actionLog.Add("ExecuteCalled"); return executeResult; }; // Act ActionResult result = BeingInvokeActionMethodWithFiltersTester(() => new MockAsyncResult(), endExecute, checkBegin: false, checkEnd: false, filters: new IActionFilter[] { filter1, filter2 }); // Assert Assert.Equal(new[] { "OnActionExecuting1", "OnActionExecuting2", "OnActionExecuted1" }, actionLog.ToArray()); Assert.Equal(shortCircuitResult, result); }
public void BeginInvokeActionMethodWithFilters_OnActionExecutingSetsResult() { // Arrange ActionResult expectedResult = new ViewResult(); ActionResult overriddenResult = new ViewResult(); bool onActionExecutingWasCalled = false; bool onActionExecutedWasCalled = false; ActionFilterImpl actionFilter = new ActionFilterImpl() { OnActionExecutingImpl = filterContext => { onActionExecutingWasCalled = true; filterContext.Result = expectedResult; }, OnActionExecutedImpl = _ => { onActionExecutedWasCalled = true; } }; Func<ActionResult> endExecute = delegate { return overriddenResult; }; // Act ActionResult result = BeingInvokeActionMethodWithFiltersTester(() => new MockAsyncResult(), endExecute, checkBegin: false, checkEnd: false, filters: new IActionFilter[] { actionFilter } ); // Assert Assert.True(onActionExecutingWasCalled); Assert.False(onActionExecutedWasCalled); Assert.Equal(expectedResult, result); }
public void BeginInvokeActionMethodWithFilters_FiltersOrderedCorrectly() { // Arrange List<string> actionLog = new List<string>(); ActionResult actionResult = new ViewResult(); Func<ActionResult> continuation = delegate { actionLog.Add("Continuation"); return actionResult; }; ActionFilterImpl filter1 = new ActionFilterImpl() { OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add("OnActionExecuting1"); }, OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add("OnActionExecuted1"); } }; ActionFilterImpl filter2 = new ActionFilterImpl() { OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add("OnActionExecuting2"); }, OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add("OnActionExecuted2"); } }; // Act ActionResult result = BeingInvokeActionMethodWithFiltersEndTester(continuation, filter1, filter2); // Assert Assert.Equal(new[] { "OnActionExecuting1", "OnActionExecuting2", "Continuation", "OnActionExecuted2", "OnActionExecuted1" }, actionLog.ToArray()); Assert.Equal(actionResult, result); }
public void BeginInvokeActionMethodWithFilters_EndExecuteThrowsOnActionExecutedException_HandledByLater() { // Arrange List<string> actionLog = new List<string>(); Exception exception = new Exception("Some exception message."); ActionResult expectedResult = new ViewResult(); Func<ActionResult> action = delegate { actionLog.Add("EndExecute"); throw exception; }; ActionFilterImpl filter1 = new ActionFilterImpl() { OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add("OnActionExecuting1"); }, OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add("OnActionExecuted1"); } }; ActionFilterImpl filter2 = new ActionFilterImpl() { OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) { actionLog.Add("OnActionExecuting2"); }, OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) { actionLog.Add("OnActionExecuted2"); Assert.Same(exception, filterContext.Exception); filterContext.ExceptionHandled = true; filterContext.Result = expectedResult; } }; // Act ActionResult result = BeingInvokeActionMethodWithFiltersEndTester(action, filter1, filter2); // Assert Assert.Equal(new[] { "OnActionExecuting1", "OnActionExecuting2", "EndExecute", "OnActionExecuted2", "OnActionExecuted1" }, actionLog.ToArray()); Assert.Equal(expectedResult, result); }
public void BeginInvokeActionMethodWithFilters_EndExecuteThrowsOnActionExecutedException_Handled() { // Arrange ViewResult expectedResult = new ViewResult(); Exception exepctedException = new Exception("Some exception message."); bool actionCalled = false; bool onActionExecutedCalled = false; ActionFilterImpl actionFilter = new ActionFilterImpl() { OnActionExecutedImpl = (filterContext) => { onActionExecutedCalled = true; Assert.Same(exepctedException, filterContext.Exception); filterContext.ExceptionHandled = true; filterContext.Result = expectedResult; } }; Func<ActionResult> action = () => { actionCalled = true; throw exepctedException; }; // Act ActionResult result = BeingInvokeActionMethodWithFiltersEndTester(action, actionFilter); // Assert Assert.True(actionCalled); Assert.True(onActionExecutedCalled); Assert.Equal(expectedResult, result); }
public void BeginInvokeActionMethodWithFilters_BeginExecuteThrowsOnActionExecutingException_Handled() { // Arrange ActionResult expectedResult = new ViewResult(); Exception expectedException = new Exception("Some exception text."); bool onActionExecutingWasCalled = false; bool onActionExecutedWasCalled = false; ActionFilterImpl actionFilter = new ActionFilterImpl() { OnActionExecutingImpl = filterContext => { onActionExecutingWasCalled = true; }, OnActionExecutedImpl = filterContext => { onActionExecutedWasCalled = true; Assert.Same(expectedException, filterContext.Exception); filterContext.ExceptionHandled = true; filterContext.Result = expectedResult; } }; Func<IAsyncResult> beginExecute = delegate { throw expectedException; }; // Act ActionResult result = BeingInvokeActionMethodWithFiltersBeginTester(beginExecute, actionFilter); // Assert Assert.True(onActionExecutingWasCalled); Assert.True(onActionExecutedWasCalled); Assert.Equal(expectedResult, result); }
public void InvokeActionMethod_SynchronousDescriptor() { // Arrange ControllerContext controllerContext = new ControllerContext(); Dictionary<string, object> parameters = new Dictionary<string, object>(); ActionResult expectedResult = new ViewResult(); Mock<ActionDescriptor> mockActionDescriptor = new Mock<ActionDescriptor>(); mockActionDescriptor.Setup(d => d.Execute(controllerContext, parameters)).Returns(expectedResult); AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker(); // Act IAsyncResult asyncResult = invoker.BeginInvokeActionMethod(controllerContext, mockActionDescriptor.Object, parameters, null, null); ActionResult returnedResult = invoker.EndInvokeActionMethod(asyncResult); // Assert Assert.Equal(expectedResult, returnedResult); }
public void FindView_ReturnsExpectedNotFoundResult_WithGetViewLocations() { // Arrange var expectedLocations = new[] { "location1", "location2" }; var context = GetActionContext(); var executor = GetViewExecutor(); var viewName = "myview"; var viewEngine = new Mock<IViewEngine>(MockBehavior.Strict); viewEngine .Setup(e => e.GetView(/*executingFilePath*/ null, "myview", /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound("myview", expectedLocations)); viewEngine .Setup(e => e.FindView(context, "myview", /*isMainPage*/ true)) .Returns(ViewEngineResult.NotFound("myview", Enumerable.Empty<string>())); var viewResult = new ViewResult { ViewName = viewName, ViewEngine = viewEngine.Object, ViewData = new ViewDataDictionary(new EmptyModelMetadataProvider()), TempData = Mock.Of<ITempDataDictionary>(), }; // Act var result = executor.FindView(context, viewResult); // Assert Assert.False(result.Success); Assert.Null(result.View); Assert.Equal(expectedLocations, result.SearchedLocations); }