C# – How to mock ModelState.IsValid using the Moq framework

asp.net-mvccmockingmoqunit testing

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?

Best Answer

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();