C# xVal测试
有人知道如何为xVal或更多的点DataAnnotations属性生成测试吗 下面是一些我想测试的代码 [元数据类型(类型(类别验证))] 公共部分类类别:CustomValidation { }C# xVal测试,c#,xval,C#,Xval,有人知道如何为xVal或更多的点DataAnnotations属性生成测试吗 下面是一些我想测试的代码 [元数据类型(类型(类别验证))] 公共部分类类别:CustomValidation { } 嗯,测试它应该很容易。对我来说,使用NUnit,它是这样的: [Test] [ExpectedException(typeof(RulesException))] public void Cannot_Save_Large_Data_In_Color() {
嗯,测试它应该很容易。对我来说,使用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的博客中得到):
这一切都过于简单化了,但还是可行的。使用MVC时更好的解决方案是MVC.DataAnnotions模型绑定器,您可以从中获得。从DefaultModelBinder构建您自己的modelbinder很容易,但无需费心,因为它已经完成了
希望这有帮助
PS.还发现了一些使用DataAnnotation的示例单元测试
[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.");
}
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);
}
}