CD *_*ith 9 validation tdd entity c#-4.0 ivalidatableobject
我有一个测试类,有几个测试,检查实体是否IsValid.我开始使用IValidatableObject自己的自定义验证,但我坚持使用正确的验证技术.
这是我的Test类:
[TestFixture]
public class StudentTests {
private static Student GetContactWithContactInfo()
{
return new Student(new TestableContactRepository())
{
Phone = "7275551111"
};
}
private static Student GetContactWithoutContactInfo()
{
return new Student(new TestableContactRepository());
}
[Test]
public void Student_Saving_StudentHasInfo_IsValid ()
{
// Arrange
Student student = GetContactWithContactInfo();
// Act
student.Save();
// Assert
Assert.IsTrue(student.IsValid);
}
[Test]
public void Student_Saving_StudentDoesNotHaveInfo_IsNotValid ()
{
// Arrange
Student student = GetContactWithoutContactInfo();
// Act
student.Save();
// Assert
Assert.IsFalse(student.IsValid);
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的实体:
public class Student : IValidatableObject
{
private readonly IContactRepository contactRepository;
public Student(IContactRepository _contactRepository)
{
contactRepository = _contactRepository;
Contacts = new List<Student>();
}
[Required]
public int Id { get; private set; }
[StringLength(10, MinimumLength = 10)]
public string Phone { get; set; }
public List<Student> Contacts { get; private set; }
public bool IsValid { get; private set; }
public void Save()
{
if (IsValidForPersistance())
{
IsValid = true;
Id = contactRepository.Save();
}
}
private bool IsValidForPersistance()
{
return Validator.TryValidateObject(this, new ValidationContext(this), null, true);
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (string.IsNullOrEmpty(Phone) && Contacts.All(c => string.IsNullOrEmpty(c.Phone)))
yield return new ValidationResult("The student or at least one contact must have a phone number entered", new[] { "Phone Number" });
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,IsValid通过调用测试来测试IsValidForPersistance.Validate最终将有更多的验证.
以上测试都使用此方法,但下面的测试也通过但不应该通过.
[Test]
public void Student_Saving_HasContactInfoWithInvalidLength_IsNotValid()
{
// Arrange
Contact student = GetContactWithoutContactInfo();
student.Phone = "string";
// Act
student.Save();
// Assert
Assert.IsFalse(student.IsValid);
}
Run Code Online (Sandbox Code Playgroud)
这里我设置了自己Phone的无效长度字符串的值.我希望验证失败,因为StringLength注释设置为最小和最多10个字符.
为什么这个过去了?
更新
自定义验证存在问题,使用更改更新了代码.除了nemesv关于private在Phone物业上没有修饰符的建议,它现在有效.我已将所有代码更新为正常工作.
nem*_*esv 17
Validator.TryValidateObject 只检查了RequiredAttributeS(以及其他类似的东西类型级别属性和IValidatableObject实现)默认情况下.
如果您需要验证所有属性一样StringLength等你需要的设置validateAllProperties方法的参数true
private bool IsValidForPersistance() {
return Validator.TryValidateObject(this,
new ValidationContext(this),
null,
true /* validateAllProperties */);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1683 次 |
| 最近记录: |