エンティティがIsValid
かどうかを確認するテストをいくつかテストしています。私はIValidatableObject
を使用して私自身のカスタム検証を行っていますが、正しい検証手法が残っています。IValidatableObjectは検証をパスしますが、StringLengthは無効です
は、これは私のテストクラスです:
[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);
}
}
これは私の実体である:あなたがIsValidForPersistance
を呼び出すことにより、IsValid
のテストのテストを見ることができるように
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" });
}
}
。 Validate
は最終的により多くの検証を行います。
上記のテストはすべてこのメソッドを使用していますが、以下のテストもパスしますが、そうしないでください。
ここでは、無効な長さの文字列の値をPhone
に設定しています。 StringLength
注釈が最小10文字まで設定されているため、検証が失敗すると思います。
これはなぜですか?
更新 カスタム検証に問題があり、変更が加えられたコードが更新されました。 nemesvがPhone
プロパティにprivate
修飾子を持たないという提案に加えて、現在は機能しています。私はすべてのコードを更新して作業しています。
にメソッドの
validateAllProperties
パラメータを設定する必要がStringLength
などのようなすべての属性を検証する必要がある場合プロジェクト。このプロジェクトでは、バリデーターと連携する追加のヘルパークラスが実装されています。 http://www.codeproject.com/Articles/256183/DataAnnotations-Validation-for-Beginner –