UnitTesting Controller DataAnnotation Validation in MVC3 : ModelState.IsValid always true ?

Testing for ModelState.IsValid when unit testing your controller is not straightforward, since the Model Binding is responsible for validating you model. But Model Binding happens in OnActionExecuted filter (and NOT when you call your controller Action method).

That means in your test context, Model Binding will not happen when you call your action method and ModelState.IsValid will always be true. But thanksfully, there is a solution below

If we have the following simplistic model :

public class UserModel
{
    [Required]
    [Display(Name = "First name")]
    public string FirstName { get; set; }

    [Required]
    [Display(Name = "Last name")]
    public string LastName { get; set; }

}

Along with the following simplistic Controller :

public class UserController : Controller
{
    //
    // GET: /User/

    public ActionResult Index()
    {
        return View("Index");
    }

    //
    // POST: /User/Create

    [HttpPost]
    public ActionResult Create(UserModel model)
    {
        if (!ModelState.IsValid)
            return View("Error");

        // perform creation (not implemented)

        // and return Index view
        return View("Index");
    }
}

The following code will not work as expected :

[TestMethod]
        public void TestErrorViewIsReturnedWhenInputIsNotValid()
        {
            // Arrange
            var expectedViewName = "Error";
            var controller = new UserController();
            var badModel = new UserModel(){FirstName = "", LastName = ""};

            // Act
            var result = controller.Create(badModel) as ViewResult;

            // Assert
            Assert.IsNotNull(result);
            Assert.AreEqual(expectedViewName, result.ViewName);
        }

When we call controller.Create(badModel), no model binding occurs and ModelState.IsValid will be true.

If we want an effective Test, what we have to do is mimic the behaviour of the model binder which is responsible for Validating the Model. :

using System.ComponentModel.DataAnnotations;

[TestMethod]
public void TestErrorViewIsReturnedWhenInputIsNotValid()
{
    // Arrange
    var expectedViewName = "Error";
    var controller = new UserController();
    var badModel = new UserModel() { FirstName = "", LastName = "" };

    // Act

    // mimic the behaviour of the model binder which is responsible for Validating the Model
    var validationContext = new ValidationContext(badModel, null, null);
    var validationResults = new List<ValidationResult>();
    Validator.TryValidateObject(badModel, validationContext, validationResults, true);
    foreach (var validationResult in validationResults)
    {
        controller.ModelState.AddModelError(validationResult.MemberNames.First(), validationResult.ErrorMessage);
    }
    var result = controller.Create(badModel) as ViewResult;

    // Assert
    Assert.IsNotNull(result);
    Assert.AreEqual(expectedViewName, result.ViewName);
}

What we do is validate the object and then feed the controller.ModelState with whatever errors we encountered.

And this is it, you can test the DataAnnotations of your model.

Many thanks to http://randomtype.ca/blog/how-to-test-modelstate-isvalid-in-asp-net-mvc/

This article is part of the GWB Archives. Original Author: Etienne Giust

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.