Unit tests on MVC validation

前端 未结 12 1223
离开以前
离开以前 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:10

    I had been having the same problem, and after reading Pauls answer and comment, I looked for a way of manually validating the view model.

    I found this tutorial which explains how to manually validate a ViewModel that uses DataAnnotations. They Key code snippet is towards the end of the post.

    I amended the code slightly - in the tutorial the 4th parameter of the TryValidateObject is omitted (validateAllProperties). In order to get all the annotations to Validate, this should be set to true.

    Additionaly I refactored the code into a generic method, to make testing of ViewModel validation simple:

        public static void ValidateViewModel(this TController controller, TViewModel viewModelToValidate) 
            where TController : ApiController
        {
            var validationContext = new ValidationContext(viewModelToValidate, null, null);
            var validationResults = new List();
            Validator.TryValidateObject(viewModelToValidate, validationContext, validationResults, true);
            foreach (var validationResult in validationResults)
            {
                controller.ModelState.AddModelError(validationResult.MemberNames.FirstOrDefault() ?? string.Empty, validationResult.ErrorMessage);
            }
        }
    

    So far this has worked really well for us.

提交回复
热议问题