我的财产定义如下:
[Required(ErrorMessage="The Year of Manufacture has to be filled")]
public int? YearOfManufacture { get; set; }
如果属性设置了所需的注释,我如何编写单元测试,测试?
答案 0 :(得分:2)
您可以使用测试助手方法在视图模型的特定实例上运行验证:
public bool TryValidate(object model, out ICollection<ValidationResult> results)
{
var context = new ValidationContext(model, serviceProvider: null, items: null);
results = new List<ValidationResult>();
return Validator.TryValidateObject(
model, context, results, validateAllProperties: true
);
}
然后在你的单元测试中:
[TestMethod]
public void YearOfManufacture_Is_Required()
{
// arrange
var sut = new MyViewModel();
sut.YearOfManufacture = null;
ICollection<ValidationResult> results;
// act
var actual = TryValidate(sut, out results);
// assert
Assert.IsFalse(actual);
}
除了使用DataAnnotations之外,您还可以查看FluentValidation.NET
,它可以让您以流畅的方式表达更复杂的验证规则,它有一个很好的integration with MVC
和testing
验证规则更容易。
答案 1 :(得分:2)
我建议FluentAssertions这样做,这样你就可以非常干净地做到这一点:
typeof(MyType)
.GetProperty("YearOfManufacture")
.Should()
.BeDecoratedWith<RequiredAttribute>("because MyType.YearOfManufacture is required.");
答案 2 :(得分:0)
如果您 - 出于任何原因 - 想要测试,属性已注释(而不是测试验证注释是否有效),您可以使用建议的扩展方法here在你的测试中:
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return (T)property .GetCustomAttributes(attrType, false).FirstOrDefault();
}
EDITED: (1)使用FirstOrDefault()而不是First()来正确处理未注释的属性。 (2)@Pavel Straka:在下面添加了更多示例代码来回答Pavel Straka的评论。
class Sample
{
[Required(ErrorMessage = "The Year of Manufacture has to be filled")]
public int? YearOfManufacture { get; set; }
public int? NotAttributedProperty { get; set; }
}
static class Annotations
{
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return (T)property.GetCustomAttributes(attrType, false).FirstOrDefault();
}
}
class Program
{
static void Main(string[] args)
{
var sampleInstance = new Sample();
var annotation = sampleInstance.GetAttributeFrom<RequiredAttribute>("YearOfManufacture");
var nullAnnotation = sampleInstance.GetAttributeFrom<RequiredAttribute>("NotAttributedProperty");
}
}