Unit tests on MVC validation

前端 未结 12 1215
离开以前
离开以前 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 07:00

    This doesn't exactly answer your question, because it abandons DataAnnotations, but I'll add it because it might help other people write tests for their Controllers:

    You have the option of not using the validation provided by System.ComponentModel.DataAnnotations but still using the ViewData.ModelState object, by using its AddModelError method and some other validation mechanism. E.g:

    public ActionResult Create(CompetitionEntry competitionEntry)
    {        
        if (competitionEntry.Email == null)
            ViewData.ModelState.AddModelError("CompetitionEntry.Email", "Please enter your e-mail");
    
        if (ModelState.IsValid)
        {
           // insert code to save data here...
           // ...
    
           return Redirect("/");
        }
        else
        {
            // return with errors
            var viewModel = new CompetitionEntryViewModel();
            // insert code to populate viewmodel here ...
            // ...
    
    
            return View(viewModel);
        }
    }
    

    This still lets you take advantage of the Html.ValidationMessageFor() stuff that MVC generates, without using the DataAnnotations. You have to make sure the key you use with AddModelError matches what the view is expecting for validation messages.

    The controller then becomes testable because the validation is happening explicitly, rather than being done automagically by the MVC framework.

提交回复
热议问题