2009-07-03 25 views
1

有誰知道如何生成的XVAL測試,或多個點的DataAnnotations屬性XVAL測試

下面是一些相同的代碼,我想測試

[MetadataType(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; } 

} 

回答

2

好,測試它應該很容易。對我來說,使用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一起使用。