How to mock ModelState.IsValid using the Moq framework?

Mazen picture Mazen · Sep 29, 2010 · Viewed 19.9k times · Source

I'm checking ModelState.IsValid in my controller action method that creates an Employee like this:

[HttpPost]
public virtual ActionResult Create(EmployeeForm employeeForm)
{
    if (this.ModelState.IsValid)
    {
        IEmployee employee = this._uiFactoryInstance.Map(employeeForm);
        employee.Save();
    }

    // Etc.
}

I want to mock it in my unit test method using Moq Framework. I tried to mock it like this:

var modelState = new Mock<ModelStateDictionary>();
modelState.Setup(m => m.IsValid).Returns(true);

But this throws an exception in my unit test case. Can anyone help me out here?

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 29, 2010

You don't need to mock it. If you already have a controller you can add a model state error when initializing your test:

// arrange
_controllerUnderTest.ModelState.AddModelError("key", "error message");

// act
// Now call the controller action and it will 
// enter the (!ModelState.IsValid) condition
var actual = _controllerUnderTest.Index();