MaxLengthAttribute 的单元测试失败

Unit Test of MaxLengthAttribute fails

我正在尝试在最大长度为 25 个字符的模型上测试数据注释验证。

我有这个型号:

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

但是这个单元测试失败了:

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

它说该对象是有效的,即使它不是。我在这里错过了什么?

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

注意 validateAllProperties 标志设置为 true。这指示验证器检查所有属性,正如名称所暗示的那样

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

强调我的

如果应用于测试的第一部分,它将失败,因为 for 循环从 0 到 25,并且字符串构建器已经有一个字符。

这按预期通过了

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

参考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.