ValidationContext的单元测试失败了吗?

时间:2013-02-24 10:42:42

标签: unit-testing validation domain-driven-design

我正在尝试对具有基类的对象进行单元测试验证。我期待3个属性(电子邮件,电话和技能> 0)验证失败,但测试失败。

BASE CLASS

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 个答案:

答案 0 :(得分:1)

创建新承包商时初始化列表。

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