Unit tests on MVC validation

前端 未结 12 1229
离开以前
离开以前 2020-12-04 06:31

How can I test that my controller action is putting the correct errors in the ModelState when validating an entity, when I\'m using DataAnnotation validation in MVC 2 Previe

12条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 06:47

    In contrast to ARM, I don't have a problem with grave digging. So here is my suggestion. It builds on the answer of Giles Smith and works for ASP.NET MVC4 (I know the question is about MVC 2, but Google doesn't discriminate when looking for answers and I cannot test on MVC2.) Instead of putting the validation code in a generic static method, I put it in a test controller. The controller has everything needed for validation. 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 validationResults = new List();
                Validator.TryValidateObject(Model, validationContext, validationResults, true);
                foreach (ValidationResult validationResult in validationResults)
                {
                    this.ModelState.AddModelError(String.Join(", ", validationResult.MemberNames), validationResult.ErrorMessage);
                }
            }
        }
    

    Of course the class does not need to be a protected innerclass, that is the way I use it now but I probably am going to reuse that class. If somewhere there is a model MyModel that is decorated with nice data annotation attributes, 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 for tests of all my models and may be able to extend it to mock a bit more about the controller or use the protected methods that a controller has.

    Hope it helps.

提交回复
热议问题