Unit Testing ASP.NET DataAnnotations validation

后端 未结 5 1070
说谎
说谎 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 08:00

    I had an issue where TestsHelper worked most of the time but not for validation methods defined by the IValidatableObject interface. The CompareAttribute also gave me some problems. That is why the try/catch is in there. The following code seems to validate all cases:

    public static void ValidateUsingReflection(T obj, Controller controller)
    {
        ValidationContext validationContext = new ValidationContext(obj, null, null);
        Type type = typeof(T);
        MetadataTypeAttribute meta = type.GetCustomAttributes(false).OfType().FirstOrDefault();
        if (meta != null)
        {
            type = meta.MetadataClassType;
        }
        PropertyInfo[] propertyInfo = type.GetProperties();
        foreach (PropertyInfo info in propertyInfo)
        {
            IEnumerable attributes = info.GetCustomAttributes(false).OfType();
            foreach (ValidationAttribute attribute in attributes)
            {
                PropertyInfo objPropInfo = obj.GetType().GetProperty(info.Name);
                try
                {
                    validationContext.DisplayName = info.Name;
                    attribute.Validate(objPropInfo.GetValue(obj, null), validationContext);
                }
                catch (Exception ex)
                {
                    controller.ModelState.AddModelError(info.Name, ex.Message);
                }
            }
        }
        IValidatableObject valObj = obj as IValidatableObject;
        if (null != valObj)
        {
            IEnumerable results = valObj.Validate(validationContext);
            foreach (ValidationResult result in results)
            {
                string key = result.MemberNames.FirstOrDefault() ?? string.Empty;
                controller.ModelState.AddModelError(key, result.ErrorMessage);
            }
        }
    }
    

提交回复
热议问题