Sponsored By Aspose - File Format APIs for .NET

Aspose are the market leader of .NET APIs for file business formats – natively work with DOCX, XLSX, PPT, PDF, MSG, MPP, images formats and many more!

Forcing MVC Model State to invalid for Unit Tests

Unit testing ASP.Net MVC applications is easier than every today. But how do you force ModelState.IsValid to be false in a unit tests?

The simple thought would be to simply create an invalid object and pass that into your action method, but this will not work. Why? Because the validation is down by the MVC pipeline prior to reaching your actual method and you do not have direct access to this.

However, we can fake it by manually adding model errors, thus getting IsValid to return false.

Imagine you have a controller which does something like below

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult CustomerFeedback(CustomerFeedbackData model)
{
    if (!ModelState.IsValid)
    {
        return Json(new ResponseModel<CustomerFeedbackData>());
    }

    emailService.CustomerFeedback(model);

    return Json(new ResponseModel<CustomerFeedbackData>(model));
}

And you wanted to create a unit test that would exercise the failing of the .IsValid check.

To accomplish this you could manually force a model error like below.

[Test]
public void CustomerFeedback_When_Model_Is_Not_Valid_Will_Return_Error_State()
{
    var controller = GetController();  // helper method to construct an instance of the controller
    var customerFeedbackData = new CustomerFeedbackData();

    // force validation error --> this is the magic sauce
    controller.ModelState.AddModelError("FirstName", "First Name is Required");

    var result = (JsonResult) controller.CustomerFeedback(customerFeedbackData);

    var asModel = (ResponseModel<CustomerFeedbackData>) result.Data;

    asModel.Success.ShouldBeFalse();
}

Long story short, you can force errors by adding them to the ModelState instance on the controller.

Till next time,

This entry was posted in MVC. Bookmark the permalink. Follow any comments here with the RSS feed for this post.