简体   繁体   中英

Model Validation from Unit Testing only works for string

I have got a class like this

Model:

public class Circle
{
    [Required(ErrorMessage = "Diameter is required")]
    public int Diameter { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Color { get; set; }
}

Testing:

[TestMethod]
public void TestCircle()
{
    Circle circle = new Circle();
    circle.Diameter = 5;
    circle.Color = "Black";
    ValidationContext contex = new ValidationContext(circle, null, null);
    Validator.ValidateObject(circle , contex);
}

I was expecting it'd fail whenever Diameter or Color is null. However, the above testing only failed when the string parameter, Color, is null. Why? How should I do in order to validate Diameter as well?

You shouldn't use the Required attribute with numeric properties. Use the Range attribute instead:

The RequiredAttribute attribute specifies that when a field on a form is validated, the field must contain a value. A validation exception is raised if the property is null, contains an empty string (""), or contains only white-space characters.

RequiredAttribute only validates against null (and empty strings), but an int is non-nullable and becomes 0 by default.

You could make it nullable (with int? ) or you could use a different kind of attribute. As DmitryG says, you could use the RangeAttribute if there's a certain range of numbers that are acceptable to you, but if not I think the only way would be a CustomValidationAttribute with a function to compare the value to zero.

EDIT: Given that it's a diameter, I guess you need to make sure it's positive, and not just unequal to zero. In this case a RangeAttribute may indeed be best, with 1 as the minimum and Int32.MaxValue as the maximum.

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