I usually unit test setup model validation, directly calling the methods of the facade System.ComponentModel.DataAnnotations.Validator.
I wrote an article on this subject http://timoch.com/blog/2013/06/unit-testing-model-validation-with-mvcs-dataannotations/
As a result, I get code like this (the article shows a cleaner and more reusable unit test base class for model verification)
[Test] [TestCaseSource("ValidationRule_Source")] public void ValidationRule(ValidateRuleSpec spec) { // Arrange var model = CreateValidPersonModel(); // Apply bad valud model.GetType().GetProperty(spec.MemberName).SetValue(model, spec.BadValue); // Act var validationResults = new List<ValidationResult>(); var success = Validator.TryValidateObject(model, new ValidationContext(model), validationResults, true); // Assert Expect(success, False); Expect(validationResults.Count, EqualTo(1)); Expect(validationResults.SingleOrDefault(r => r.MemberNames.Contains(spec.MemberName)), Not.Null); } public IEnumerable<ValidateRuleSpec> ValidationRule_Source() { yield return new ValidateRuleSpec() { BadValue = null, MemberName = "FirstName" }; yield return new ValidateRuleSpec() { BadValue = string.Empty, MemberName = "FirstName" }; yield return new ValidateRuleSpec() { BadValue = null, MemberName = "LastName" }; /* ... */ }
I donβt like trusting code to work, so I systematically write unit test for my model validation code. However, I trust the framework / model middleware to perform the validation. This unit test allows me to write a controller that trusts validation in order.
source share