简体   繁体   中英

Unit Test of MaxLengthAttribute fails

I am attempting to test data annotations validation on a model where the max length is 25 characters.

I have this model:

public class ContactRequest
{
    [MaxLength(25, ErrorMessage = "String exceeds maximum length of 25")]
    public string DisplayName { get; set; }
}

But this unit test fails:

[Test]
public void Max25CharsTest()
{
    // Arrange
    var stringBuilder = new StringBuilder("a");

    for (var i = 0; i < 25; i++)
    {
        stringBuilder.Append("a");
    }

    var model = new ContactRequest { DisplayName = stringBuilder.ToString() };
    var context = new ValidationContext(model);

    var results = new List<ValidationResult>();

    // Act
    var actual = Validator.TryValidateObject(model, context, results);

    // Assert
    Assert.True(actual, "Expects validation to pass");

    // Append characters
    stringBuilder.Append("asdf");
    model.DisplayName = stringBuilder.ToString();
    results.Clear();
    actual = Validator.TryValidateObject(model, context, results);
    Assert.False(actual, "Expects validation to fail"); // Fails here
}

It says that the object is valid even though it is not. What am I missing here?

//...omitted for brevity

// Append characters
stringBuilder.Append("asdf");
model.DisplayName = stringBuilder.ToString() ;            
results.Clear();
actual = Validator.TryValidateObject(model, context, results, validateAllProperties: true);
Assert.IsFalse(actual, "Expects validation to fail");

Note the validateAllProperties flag set to true . This instructs the validator to check all properties as the name would imply

true to validate all properties; if false, only required attributes are validated ..

emphasis mine

If applied to the first part of the test it would fail since the for loop goes from 0 to 25 and the string builder already has a character.

This passes as expected

public void Max25CharsTest() {
    // Arrange
    var stringBuilder = new StringBuilder("a");

    for (var i = 0; i < 24; i++) { //<-- changed this to 24
        stringBuilder.Append("a");
    }

    var model = new ContactRequest { DisplayName = stringBuilder.ToString() };
    var context = new ValidationContext(model);
    var results = new List<ValidationResult>();

    // Act
    var actual = Validator.TryValidateObject(model, context, results, validateAllProperties: true);

    // Assert
    Assert.IsTrue(actual, "Expects validation to pass");

    // Append characters
    stringBuilder.Append("asdf");
    model.DisplayName = stringBuilder.ToString();
    results.Clear();
    actual = Validator.TryValidateObject(model, context, results, validateAllProperties: true);
    Assert.IsFalse(actual, "Expects validation to fail");
}

Reference TryValidateObject(Object, ValidationContext, ICollection<ValidationResult>, Boolean)

This method evaluates each ValidationAttribute instance that is attached to the object type. It also checks whether each property that is marked with RequiredAttribute is provided. It validates the property values of the object if validateAllProperties is true but does not recursively validate properties of the objects returned by the properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM