Search
Close this search box.

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

Tuesday, March 13, 2012 3:09 AM

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’s .NET notes

Related Posts