I have a submit model with a property of type decimal that represents a percentage. I use the range attribute to only allow values from 0 to 100. I have a unit test where I use the Validator to test this validation on the submit model. However, when I pass in an input that’s outside the valid range, the validation result does not have any errors.
public class SubmitModel { [Range(0d, 100d)] public decimal Percentage { get; set; } }
The sample submit model
[TestFixture] public class SubmitModelTests { [Test] public void InvalidInputs_Should_Have_ValidationErrors([Values(-0.01, 100.01)] decimal percentage) { var submitModel = new SubmitModel { Percentage = percentage }; var validationContext = new ValidationContext(submitModel); var validationResults = new List<ValidationResult>(); Validator.TryValidateObject(submitModel, validationContext, validationResults); validationResults.Count.Should().Be(1); } }
The unit test should give 1 error but the test fails as there is no error.
For the Validator to validate the properties, you need to tell it so. The Validator has an overload method TryValidateObject with an additional flag validateAllProperties. Set this to true and it will validate the properties and pass the test.
Very nice post. I simply stumbled upon your blog and wished to say that I’ve truly enjoyed browsing your weblog posts. After all I will be subscribing for your feed and I hope you write once more very soon!