簡體   English   中英

ValidationContext的單元測試失敗?

[英]Unit test of ValidationContext is failing?

我正在嘗試對具有基類的對象進行單元測試驗證。 我期望3個屬性(電子郵件,電話和技能> 0)無法通過驗證,但是測試失敗。

基礎類

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.");
    }

測試

[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);
    }

創建新承包商時初始化您的列表。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM