public void When_ModelState_Invalid_And_Controller_Not_Found_Set_Result_Null() { // arrange var attribute = new ValidateModelStateAttribute(); var actionContext = new ActionContext { HttpContext = new DefaultHttpContext(), ActionDescriptor = new ActionDescriptor(), RouteData = new RouteData() }; var context = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(new List <IFilterMetadata>()), new Dictionary <string, object> { { "model", new { Id = 13, Name = " Some name" } } }, null); context.ModelState.AddModelError(string.Empty, "Message"); // act attribute.OnActionExecuting(context); // assert Assert.Null(context.Result); }
public void When_ModelState_Invalid_Set_Result_Model() { // arrange var attribute = new ValidateModelStateAttribute(); var controller = new TestController(); var viewModelId = 13; var model = new { Id = viewModelId }; var actionContext = new ActionContext { HttpContext = new DefaultHttpContext(), ActionDescriptor = new ActionDescriptor(), RouteData = new RouteData() }; var context = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(new List <IFilterMetadata>()), new Dictionary <string, object> { { "model", model } }, controller); context.ModelState.AddModelError(string.Empty, "Message"); // act attribute.OnActionExecuting(context); // assert Assert.True(context.Result != null); var resultModel = (context.Result as ViewResult)?.Model; Assert.True(Convert.ToInt32(resultModel?.GetType().GetProperty("Id").GetValue(resultModel)) == viewModelId); }
public void When_ModelState_Is_Valid_Set_Result_Null() { // arrange var attribute = new ValidateModelStateAttribute(); var controller = new TestController(); var actionContext = new ActionContext { HttpContext = new DefaultHttpContext(), ActionDescriptor = new ActionDescriptor(), RouteData = new RouteData() }; var context = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(new List <IFilterMetadata>()), new Dictionary <string, object> { { "model", new { Id = 13, Name = " Some name" } } }, controller); // act attribute.OnActionExecuting(context); // assert Assert.Null(context.Result); }
public void ThrowsException_IfContextActionArgumentsIsNul() { // Arrange // Prepare the actionArguments with a null action argument var actionArguments = new Dictionary <string, object>(); actionArguments.Add("arg1", null); var actionContext = new ActionContext( Mock.Of <HttpContext>(), Mock.Of <RouteData>(), Mock.Of <ActionDescriptor>() ); var actionExecutingContext = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(), actionArguments, Mock.Of <Controller>() ); // Prepare the IValidatorFactory with the RequestModelBasicValidator var mockValidatorFactory = new Mock <IValidatorFactory>(); mockValidatorFactory.Setup(vm => vm.GetValidator(typeof(RequestModelBasic))).Returns(new RequestModelBasicValidator()); var validateModelStateAttribute = new ValidateModelStateAttribute(mockValidatorFactory.Object, _logger); // Act & Assert (Exception is thrown) var ex = Assert.Throws <Exception>(() => validateModelStateAttribute.OnActionExecuting(actionExecutingContext)); // Assert (Exception message) Assert.Equal("ConsistentApiResponseErrors ValidateModelStateAttribute: The ActionArgument.Value is null", ex.Message); }
public void InvalidModelStateShouldReturnBadRequestObjectResult() { var httpContext = new DefaultHttpContext(); var context = new ActionExecutingContext( new ActionContext { HttpContext = httpContext, RouteData = new RouteData(), ActionDescriptor = new ActionDescriptor(), }, new List <IFilterMetadata>(), new Dictionary <string, object>(), new Mock <Controller>().Object); context.ModelState.AddModelError("id", "missing"); // Act ValidateModelStateAttribute validateModelStateAttribute = this.CreateValidateModelStateAttribute(); validateModelStateAttribute.OnActionExecuting(context); Assert.NotNull(context); Assert.IsType <BadRequestObjectResult>(context.Result); // Assert }
public void When_ModelState_Invalid_Model_Not_Exist_Set_Result_Null() { // arrange var attribute = new ValidateModelStateAttribute(); var controller = new TestController(); var actionContext = new ActionContext { HttpContext = new DefaultHttpContext(), ActionDescriptor = new ActionDescriptor(), RouteData = new RouteData() }; var context = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(new List <IFilterMetadata>()), new Dictionary <string, object>(), controller); context.ModelState.AddModelError(string.Empty, "Message"); // act attribute.OnActionExecuting(context); // assert Assert.Null(context.Result); }
public void OnActionExecutingValid() { var validAttr = new ValidateModelStateAttribute(); var aec = MockHelpers.ActionExecutingContext(); validAttr.OnActionExecuting(aec); Assert.True(true); }
public async Task OnActionExecutingAsyncValid() { var validAttr = new ValidateModelStateAttribute(); var aec = MockHelpers.ActionExecutingContext(); await validAttr.OnActionExecutionAsync(aec, null); Assert.True(true); }
private void ValidModelStateDoesNothing() { var context = ActionFilterFactory.CreateActionExecutingContext(); var filter = new ValidateModelStateAttribute(); filter.OnActionExecuting(context); Assert.Null(context.Result); }
public void ModelStateIValid_ShouldNotSetResponse() { var fixture = new Fixture(); var sut = new ValidateModelStateAttribute(); var actionContext = new HttpActionContext(); sut.OnActionExecuting(actionContext); var response = actionContext.Response; Assert.IsNull(response); }
public void Setup() { _actionContext = new ActionContext { HttpContext = new DefaultHttpContext(), RouteData = new RouteData(), ActionDescriptor = new ActionDescriptor() }; _actionExecutingContext = new ActionExecutingContext(_actionContext, new List <IFilterMetadata>(), new Mock <IDictionary <string, object> >().Object, null); _systemUnderTest = new ValidateModelStateAttribute(); }
public void ThrowsException_IfContextIsNull() { // Arrange ActionExecutingContext actionExecutingContext = null; // Prepare the IValidatorFactory with the RequestModelBasicValidator var mockValidatorFactory = new Mock <IValidatorFactory>(); mockValidatorFactory.Setup(vm => vm.GetValidator(typeof(RequestModelBasic))).Returns(new RequestModelBasicValidator()); var validateModelStateAttribute = new ValidateModelStateAttribute(mockValidatorFactory.Object, _logger); // Act & Assert (Exception is thrown) var ex = Assert.Throws <Exception>(() => validateModelStateAttribute.OnActionExecuting(actionExecutingContext)); // Assert (Exception message) Assert.Equal("ConsistentApiResponseErrors ValidateModelStateAttribute: The context is null", ex.Message); }
public void Should_Return_BadRequest_If_ModelState_Invalid() { // arrange var filter = new ValidateModelStateAttribute(); var context = new HttpActionContext( new HttpControllerContext(new HttpConfiguration(), new HttpRouteData(new HttpRoute("SomePattern")), new HttpRequestMessage()), new ReflectedHttpActionDescriptor()); context.ModelState.AddModelError("foo", "some error"); // act filter.OnActionExecuting(context); // assert Assert.NotNull(context.Response); Assert.Equal(HttpStatusCode.BadRequest, context.Response.StatusCode); }
public void ValidationFilterAttributeTest_Valid_ResultIsNull() { // Arrange var httpContext = new DefaultHttpContext(); var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); var actionExecutingContext = new ActionExecutingContext( actionContext, filters: new List <IFilterMetadata>(), // for majority of scenarios you need not worry about populating this parameter actionArguments: new Dictionary <string, object>(), // if the filter uses this data, add some data to this dictionary controller: null); // since the filter being tested here does not use the data from this parameter, just provide null var validationFilter = new ValidateModelStateAttribute(); // Act // Add an error into model state on purpose to make it invalid validationFilter.OnActionExecuting(actionExecutingContext); // Assert Assert.Null(actionExecutingContext.Result); }
public void OnActionExecuting_WithValidModelStrate_ShouldReturnNothing() { var mockController = new Mock <Controller>(); var mockContext = new Mock <ActionExecutingContext>( new ActionContext(new DefaultHttpContext(), new Microsoft.AspNetCore.Routing.RouteData(), new ActionDescriptor()), new List <IFilterMetadata>(), new Dictionary <string, object>(), mockController.Object); mockContext.SetupGet(context => context.Controller) .Returns(mockController.Object); var filter = new ValidateModelStateAttribute(); filter.OnActionExecuting(mockContext.Object); Assert.IsNull(mockContext.Object.Result); }
public void Should_Return_BadRequest_If_ModelState_Invalid() { // arrange var filter = new ValidateModelStateAttribute(); var context = new HttpActionContext( new HttpControllerContext(new HttpConfiguration(), new HttpRouteData(new HttpRoute("SomePattern")), new HttpRequestMessage()), new ReflectedHttpActionDescriptor()); context.ModelState.AddModelError("foo", "some error"); // act filter.OnActionExecuting(context); // assert Assert.NotNull(context.Response); Assert.Equal(HttpStatusCode.BadRequest, context.Response.StatusCode); }
public void ModelStateIsNotValid_ShouldSetResponseToBadRequest() { var fixture = new Fixture(); var sut = new ValidateModelStateAttribute(); var actionContext = new HttpActionContext { ControllerContext = new HttpControllerContext { Request = new HttpRequestMessage() } }; actionContext.ModelState.AddModelError(fixture.Create <string>(), fixture.Create <string>()); sut.OnActionExecuting(actionContext); var response = actionContext.Response; Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); }
private void InvalidModelStateSetsBadRequestResult() { var context = ActionFilterFactory.CreateActionExecutingContext(); context.ModelState.AddModelError("key1", "error1"); var filter = new ValidateModelStateAttribute(); filter.OnActionExecuting(context); Assert.NotNull(context.Result); Assert.IsType <BadRequestObjectResult>(context.Result); Assert.IsType <Error>(((BadRequestObjectResult)context.Result).Value); var error = ((BadRequestObjectResult)context.Result).Value as Error; var guid = Guid.Empty; Assert.True(Guid.TryParse(error.Id, out guid)); Assert.Equal("key1", error.Messages.First().Key); Assert.Equal("error1", error.Messages.First().Message); }
public void ValidationFilterAttributeTest_ModelStateErrors_ResultInBadRequestResult() { // Arrange var httpContext = new DefaultHttpContext(); var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); var actionExecutingContext = new ActionExecutingContext( actionContext, filters: new List <IFilterMetadata>(), // for majority of scenarios you need not worry about populating this parameter actionArguments: new Dictionary <string, object>(), // if the filter uses this data, add some data to this dictionary controller: null); // since the filter being tested here does not use the data from this parameter, just provide null var validationFilter = new ValidateModelStateAttribute(); // Act // Add an error into model state on purpose to make it invalid actionContext.ModelState.AddModelError("Error", "Some random error happened."); validationFilter.OnActionExecuting(actionExecutingContext); // Assert var jsonResult = Assert.IsType <BadRequestObjectResult>(actionExecutingContext.Result); Assert.Equal(400, jsonResult.StatusCode); }
private void InvalidModelStateSetsBadRequestResultForMultipleErrors() { var context = ActionFilterFactory.CreateActionExecutingContext(); context.ModelState.AddModelError("key1", "error1"); context.ModelState.AddModelError("key2", "error2"); context.ModelState.AddModelError("key3", "error3"); var filter = new ValidateModelStateAttribute(); filter.OnActionExecuting(context); Assert.NotNull(context.Result); Assert.IsType <BadRequestObjectResult>(context.Result); Assert.IsType <Error>(((BadRequestObjectResult)context.Result).Value); var error = ((BadRequestObjectResult)context.Result).Value as Error; Assert.Equal(3, error.Messages.Count()); Assert.Equal("error1", error.Messages.Where(m => m.Key == "key1").Single().Message); Assert.Equal("error2", error.Messages.Where(m => m.Key == "key2").Single().Message); Assert.Equal("error3", error.Messages.Where(m => m.Key == "key3").Single().Message); }
public void SetsResultToBadRequest_IfContextModelStateContainErrors() { // Arrange // Prepare the actionArguments with null actionArgument var modelState = new ModelStateDictionary(); modelState.AddModelError("Error_1", "Input string '1.3' is not a valid integer. Path 'userId', line 2, position 17."); modelState["Error_1"].RawValue = "1.3"; modelState.AddModelError("Error_2", "Could not convert string to DateTime: 2018:10. Path 'momentsDate', line 4, position 28."); var actionContext = new ActionContext( Mock.Of <HttpContext>(), Mock.Of <RouteData>(), Mock.Of <ActionDescriptor>(), modelState ); var actionExecutingContext = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(), new Dictionary <string, object>(), Mock.Of <Controller>() ); // Prepare the IValidatorFactory with the RequestModelBasicValidator var mockValidatorFactory = new Mock <IValidatorFactory>(); mockValidatorFactory.Setup(vm => vm.GetValidator(typeof(RequestModelBasic))).Returns(new RequestModelBasicValidator()); var validateModelStateAttribute = new ValidateModelStateAttribute(mockValidatorFactory.Object, _logger); // Act validateModelStateAttribute.OnActionExecuting(actionExecutingContext); // Assert Assert.IsType <BadRequestObjectResult>(actionExecutingContext.Result); }
public void SetsResultToNull_IfRequesModelHasNoValidator() { // Arrange // Prepare the actionArguments using the class RequestModelWithoutValidator: var actionArguments = new Dictionary <string, object>(); actionArguments.Add("arg1", new RequestModelWithoutValidator() { Id = 1, Message = string.Empty, CreatedOn = DateTime.Now }); var actionContext = new ActionContext( Mock.Of <HttpContext>(), Mock.Of <RouteData>(), Mock.Of <ActionDescriptor>() ); var actionExecutingContext = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(), actionArguments, Mock.Of <Controller>() ); // Prepare the IValidatorFactory with the RequestModelBasicValidator var mockValidatorFactory = new Mock <IValidatorFactory>(); mockValidatorFactory.Setup(vm => vm.GetValidator(typeof(RequestModelBasic))).Returns(new RequestModelBasicValidator()); var validateModelStateAttribute = new ValidateModelStateAttribute(mockValidatorFactory.Object, _logger); // Act validateModelStateAttribute.OnActionExecuting(actionExecutingContext); // Assert Assert.Null(actionExecutingContext.Result); }
public void SetsResultToBadRequest_IfRequesModelIsInvalid() { // Arrange // Prepare the actionArguments with invalid Id number (0) var actionArguments = new Dictionary <string, object>(); actionArguments.Add("arg1", new RequestModelBasic() { Id = 0, Message = "", CreatedOn = DateTime.Now }); var actionContext = new ActionContext( Mock.Of <HttpContext>(), Mock.Of <RouteData>(), Mock.Of <ActionDescriptor>() ); var actionExecutingContext = new ActionExecutingContext( actionContext, new List <IFilterMetadata>(), actionArguments, Mock.Of <Controller>() ); // Prepare the IValidatorFactory with the RequestModelBasicValidator var mockValidatorFactory = new Mock <IValidatorFactory>(); mockValidatorFactory.Setup(vm => vm.GetValidator(typeof(RequestModelBasic))).Returns(new RequestModelBasicValidator()); var validateModelStateAttribute = new ValidateModelStateAttribute(mockValidatorFactory.Object, _logger); // Act validateModelStateAttribute.OnActionExecuting(actionExecutingContext); // Assert Assert.IsType <BadRequestObjectResult>(actionExecutingContext.Result); }
public void ActionContextIsNull_ShouldThrowException() { var sut = new ValidateModelStateAttribute(); Assert.Throws <ArgumentNullException>(() => sut.OnActionExecuting(null)); }
public ValidateModelStateAttributeTests() { this.attribute = new ValidateModelStateAttribute(); this.context = this.GetActionExecutingContext(); }
/// <summary> /// Initialises a new instance of the <see cref="ValidateModelStateAttributeTests"/> class. /// </summary> /// <remarks> /// With Xunit the entire test class is initialized again for every test method. /// </remarks> /// <param name="factory">The WebApplicationFactory to use when creating a test server.</param> public ValidateModelStateAttributeTests() { target = new ValidateModelStateAttribute(); }