Unit tests on MVC validation

前端 未结 12 1222
离开以前
离开以前 2020-12-04 06:31

How can I test that my controller action is putting the correct errors in the ModelState when validating an entity, when I\'m using DataAnnotation validation in MVC 2 Previe

12条回答
  •  悲哀的现实
    2020-12-04 07:12

    I'm using ModelBinders in my test cases to be able to update model.IsValid value.

    var form = new FormCollection();
    form.Add("Name", "0123456789012345678901234567890123456789");
    
    var model = MvcModelBinder.BindModel(controller, form);
    
    ViewResult result = (ViewResult)controller.Add(model);
    

    With my MvcModelBinder.BindModel method as follows (basically the same code used internally in the MVC framework):

            public static TModel BindModel(Controller controller, IValueProvider valueProvider) where TModel : class
            {
                IModelBinder binder = ModelBinders.Binders.GetBinder(typeof(TModel));
                ModelBindingContext bindingContext = new ModelBindingContext()
                {
                    FallbackToEmptyPrefix = true,
                    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel)),
                    ModelName = "NotUsedButNotNull",
                    ModelState = controller.ModelState,
                    PropertyFilter = (name => { return true; }),
                    ValueProvider = valueProvider
                };
    
                return (TModel)binder.BindModel(controller.ControllerContext, bindingContext);
            }
    

提交回复
热议问题