I have a test class with a couple of tests that check if an IsValid object exists. I switched to using IValidatableObject from my own custom validation, but I followed the correct validation technique.
This is my test class:
[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 () {
This is my essence:
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" }); } }
How can you test the test for IsValid by calling IsValidForPersistance . Validate will ultimately get a lot of validation.
All of the above tests pass using this method, but this test below also passes, but should not.
[Test] public void Student_Saving_HasContactInfoWithInvalidLength_IsNotValid() {
Here I set my own Phone value to an invalid string length. I expect the check to fail due to the StringLength annotation specified in minutes and not more than 10 characters.
Why is this happening?
Update There was a problem with user verification, the code with the change was updated. Along with the nemesv suggestion that there is no private modifier in the Phone property, it now works. I updated all the code to work.
Cd smith
source share