如何测试受保护的方法?

时间:2018-11-09 02:28:11

标签: c# unit-testing model-view-controller

我写了一个costumer属性,该属性取决于另一个属性。我必须进行单元测试,但方法受到保护。我该如何测试?

public class PWCustomerAttribute : ValidationAttribute
{
    public string name;
    public string prename;
    public string emaill;

    public PWCustomerAttribute(string nom, string prenom, string email) : base() {
        name = nom;
        prename = prenom;
        emaill = email;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
           var property = validationContext.ObjectType.GetProperty(name);
            if (property == null) { throw new ArgumentException("Property with this name not found"); }
            var nameV = (string)property.GetValue(validationContext.ObjectInstance);

            property = validationContext.ObjectType.GetProperty(prename);
            if (property == null) { throw new ArgumentException("Property with this name not found"); }
            var prenameV = (string)property.GetValue(validationContext.ObjectInstance);

            property = validationContext.ObjectType.GetProperty(emaill);
            if (property == null) { throw new ArgumentException("Property with this name not found"); }
            var emaillV = (string)property.GetValue(validationContext.ObjectInstance);

            string chaine = value.ToString();
            foreach (string s in ChainAValider(chaine)) {
                if (nameV.Contains(s)||prenameV.Contains(s)|| emaillV.Contains(s))
                {
                    var msgErreur = FormatErrorMessage(validationContext.DisplayName);

                    return new ValidationResult(msgErreur);
                }
            }
        }


        return ValidationResult.Success;
    }

我的测试:

[TestMethod]
    public void AttibuteTest()
    {

        string firstName = "Yaaaaaa";
        string lastname = "Donald";
        string Email = "a@a.com";


        var value = "1!Yaaaaaa"; 
        var context = new ValidationContext(value);
        var attrib = new PWCustomerAttribute(firstName, lastname, Email);
          var results = new List<ValidationResult>();

          var result = attrib.IsValid(value, context);//, context);

    }

0 个答案:

没有答案