首页
学习
活动
专区
圈层
工具
发布

xVal测试
EN

Stack Overflow用户
提问于 2009-07-03 13:54:10
回答 1查看 194关注 0票数 1

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

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

MetadataType(typeof(CategoryValidation))公共分部类类别: CustomValidation {}

代码语言:javascript
复制
public class CategoryValidation
{
    [Required]
    public string CategoryId { get; set; }

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

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

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2009-07-13 14:20:35

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

代码语言:javascript
复制
    [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构建了一个验证运行器,并且有一种调用它的方法。如果你不这样认为,这里有一个我用来测试的非常简单的方法(我从Steve Sanderson的博客上删掉的):

代码语言:javascript
复制
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);
    }
}

在上面的小示例中,我这样调用runner:

代码语言:javascript
复制
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时,一个更好的解决方案是可以从codeplex获得的Mvc.DataAnnotions模型绑定器。从DefaultModelBinder构建自己的模型绑定器很容易,但不需要麻烦,因为它已经完成了。

希望这能有所帮助。

PS。我还找到了this site,它有一些使用DataAnnotations的样例单元测试。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1079467

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档