I like to test data attributes on models and view models outside the controller context. I did this by writing my own version of TryUpdateModel, which does not need a controller and can be used to populate the ModelState dictionary.
Here is my TryUpdateModel method (mostly taken from the source code of the .NET MVC controller):
private static ModelStateDictionary TryUpdateModel<TModel>(TModel model, IValueProvider valueProvider) where TModel : class { var modelState = new ModelStateDictionary(); var controllerContext = new ControllerContext(); var binder = ModelBinders.Binders.GetBinder(typeof(TModel)); var bindingContext = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType( () => model, typeof(TModel)), ModelState = modelState, ValueProvider = valueProvider }; binder.BindModel(controllerContext, bindingContext); return modelState; }
This can then be easily used in the unit test as follows:
// Arrange var viewModel = new AddressViewModel(); var addressValues = new FormCollection { {"CustomerName", "Richard"} }; // Act var modelState = TryUpdateModel(viewModel, addressValues); // Assert Assert.False(modelState.IsValid);
Richard Garside Feb 26 '14 at 13:55 2014-02-26 13:55
source share