【问题标题】:xVal testingxVal 测试
【发布时间】:2009-07-03 13:54:10
【问题描述】:

有谁知道如何为 xVal 生成测试,或者更多的是 DataAnnotations 属性

这是一些我想测试的相同代码

[元数据类型(typeof(CategoryValidation))] 公共部分类类别:CustomValidation { }

public class CategoryValidation
{
    [Required]
    public string CategoryId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    [StringLength(4)]
    public string CostCode { get; set; }

}

【问题讨论】:

    标签: c# xval


    【解决方案1】:

    嗯,测试它应该很容易。对我来说,使用 NUnit 是这样的:

        [Test]
        [ExpectedException(typeof(RulesException))]
        public void Cannot_Save_Large_Data_In_Color()
        {
    
            var scheme = ColorScheme.Create();
            scheme.Color1 = "1234567890ABCDEF";
            scheme.Validate();
            Assert.Fail("Should have thrown a DataValidationException.");
        }
    

    这假设您已经为 DataAnnotations 构建了一个验证运行器,并且有一种调用它的方法。如果你不在这里,我会用一个非常简单的方法来测试(我从史蒂夫·桑德森的博客中摘录):

    internal static class DataAnnotationsValidationRunner
    {
        public static IEnumerable<ErrorInfo> GetErrors(object instance)
        {
            return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                   from attribute in prop.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(prop.GetValue(instance))
                   select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
        }
    }
    

    在上面的小示例中,我这样称呼跑步者:

    public class ColorScheme
    {
         [Required]
         [StringLength(6)]
         public string Color1 {get; set; }
    
         public void Validate()
         {
             var errors = DataAnnotationsValidationRunner.GetErrors(this);
             if(errors.Any())
                 throw new RulesException(errors);
         }
    }
    

    这一切都过于简单但有效。使用 MVC 时更好的解决方案是 Mvc.DataAnnotions 模型绑定器,您可以从 codeplex 获得。从 DefaultModelBinder 构建自己的模型绑定器很容易,但由于已经完成,因此无需费心。

    希望这会有所帮助。

    PS。还发现 this site 有一些使用 DataAnnotations 的示例单元测试。

    【讨论】:

      猜你喜欢
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-31
      相关资源
      最近更新 更多