Unit Testing ASP.NET DataAnnotations validation

后端 未结 5 1067
说谎
说谎 2020-12-02 07:28

I am using DataAnnotations for my model validation i.e.

[Required(ErrorMessage="Please enter a name")]
public string Name { get; set; }
5条回答
  •  无人及你
    2020-12-02 07:53

    I like to test the data attributes on my models and view models outside the context of the controller. I've done this by writing my own version of TryUpdateModel that doesn't need a controller and can be used to populate a ModelState dictionary.

    Here is my TryUpdateModel method (mostly taken from the .NET MVC Controller source code):

    private static ModelStateDictionary TryUpdateModel(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 a unit test like this:

    // Arrange
    var viewModel = new AddressViewModel();
    var addressValues = new FormCollection
    {
        {"CustomerName", "Richard"}
    };
    
    // Act
    var modelState = TryUpdateModel(viewModel, addressValues);
    
    // Assert
    Assert.False(modelState.IsValid);
    

提交回复
热议问题