2013-02-24 64 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 2013-02-24 18:41:56

+0

沒問題,我一直這樣做;-) – stephenl 2013-02-24 23:09:54

+0

您可能還想考慮使用構造函數來執行不變量,而不是依賴驗證庫。如果你用'public Constructor(string firstName,string lastName,string phone,string email,Skill skill)替換了默認的構造函數''你正在簡化你的類,並使構造更加明確。 – stephenl 2013-02-25 01:00:50