views:

30

answers:

1

I am checking that the ModelState.IsValid in my action method that create the Employee

[HttpPost]
        public virtual ActionResult Create(EmployeeForm employeeForm)
        {
            if (this.ModelState.IsValid)
            {
                try
                {
                        IEmployee employee = this._uiFactoryInstance.Map(employeeForm);
                        employee.Save();
                }
                catch (Exception exception)
                {
                    // do anything
                }
            }

            return ...
        }

and I wanna mock it in my unit test method using Moq Framework I try to mock it like that

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

but it throw an exception in my unit test case any one can help

+2  A: 

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();
Darin Dimitrov
thanks for ur nice solution
Mazen