2013-02-24 4 views
0

기본 클래스가있는 객체에 단위 테스트 유효성 검사를 시도하고 있습니다. 유효성 검사에 실패하는 3 가지 속성 (이메일, 전화 및 기술> 0)이 필요하지만 테스트가 실패합니다.ValidationContext의 단위 테스트가 실패 했습니까?

기본 클래스

public abstract class Person : Entity 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string UserName { get; set; } 
    public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } } 
    public string Email { get; set; } 
    public string Phone { get; set; } 
    public DateTime DateAdded { get; set; } 
    public bool Active { get; set; }   
} 

파생 클래스

public class Contractor : Person, IValidatableObject 
{ 
    public Address Address { get; set; } 
    public List<Skill> SkillSet { get; set; } 
    public DateTime? NextAvailableDate { get; set; } 

    public Contractor() 
    { 

    } 

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) 
    { 
     if (string.IsNullOrWhiteSpace(base.FirstName)) 
      yield return new ValidationResult("The First Name field cannot be empty."); 

     if (string.IsNullOrWhiteSpace(base.LastName)) 
      yield return new ValidationResult("The Last Name field cannot be empty."); 

     if (string.IsNullOrWhiteSpace(base.Email)) 
      yield return new ValidationResult("The Email field cannot be empty."); 

     if (string.IsNullOrWhiteSpace(base.Phone)) 
      yield return new ValidationResult("The Phone field cannot be empty."); 

     if (SkillSet.Count() < 1) 
      yield return new ValidationResult("A contractor must have at least one skill."); 
    } 

TEST

[TestMethod] 
    public void contractor_is_missing_email_phone_skill_when_created() 
    { 
     //Arrange 
     Contractor contractor = new Contractor { FirstName = "abc", LastName = "def" }; 

     //Act 
     ValidationContext context = new ValidationContext(contractor); 
     IEnumerable<ValidationResult> result = contractor.Validate(new ValidationContext(contractor)); 
     List<ValidationResult> r = new List<ValidationResult>(result); 

     //Assert 
     Assert.IsTrue(r.Count == 3); 
    } 

답변

1

새 계약자를 만들 때 목록을 초기화한다.

public Contractor() 
    { 
     SkillSet = new List<Skill>(); 
    } 
+0

감사합니다. 다되었습니다! 내가 그것을 놓쳤다라고 생각하고있다! – Greg

+0

문제는 없습니다. 항상 그렇습니다 .--) – stephenl

+0

유효성 검증 라이브러리를 사용하는 대신 생성자를 사용하여 invariant를 적용하는 것이 좋습니다. 기본 생성자를'public constructor (string firstName, string lastName, string phone, string email, Skill skill) '으로 바꾸면 클래스를 단순화하고 구조를보다 명확하게 만듭니다. – stephenl

관련 문제