Unlike ARM, I have no problem digging seriously. So here is my suggestion. It is based on Giles Smith's answer and works in ASP.NET MVC4 (I know that it is about MVC 2, but Google makes no difference when searching for answers, and I cannot check for MVC2.) Instead of putting the verification code in general static method, I put it in a test controller. The controller has everything you need to check. So, the test controller looks like this:
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Wbe.Mvc; protected class TestController : Controller { public void TestValidateModel(object Model) { ValidationContext validationContext = new ValidationContext(Model, null, null); List<ValidationResult> validationResults = new List<ValidationResult>(); Validator.TryValidateObject(Model, validationContext, validationResults, true); foreach (ValidationResult validationResult in validationResults) { this.ModelState.AddModelError(String.Join(", ", validationResult.MemberNames), validationResult.ErrorMessage); } } }
Of course, a class does not have to be a protected inner class, so I'm using it now, but I'm probably going to reuse this class. If somewhere there is a MyModel model that is decorated with beautiful attributes of data annotation, then the test looks something like this:
[TestMethod()] public void ValidationTest() { MyModel item = new MyModel(); item.Description = "This is a unit test"; item.LocationId = 1; TestController testController = new TestController(); testController.TestValidateModel(item); Assert.IsTrue(testController.ModelState.IsValid, "A valid model is recognized."); }
The advantage of this setup is that I can reuse the test controller to test all my models and maybe expand it to make fun of the controller information a bit or use the protected methods that the controller has.
Hope this helps.
Albert Mar 21 '13 at 20:38 2013-03-21 20:38
source share