有谁知道如何为xVal生成测试,或者知道如何为DataAnnotations属性生成测试
下面是我想测试的一些相同的代码
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; }
}发布于 2009-07-13 14:20:35
好吧,测试它应该很容易。对我来说,使用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构建了一个验证运行器,并且有一种调用它的方法。如果你不这样认为,这里有一个我用来测试的非常简单的方法(我从Steve Sanderson的博客上删掉的):
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:
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的样例单元测试。
https://stackoverflow.com/questions/1079467
复制相似问题