Dilma
Dilma

Reputation: 645

ASP.Net mvc2 ModelStateDictionary Isvalid mocking using Moq

I am new to use moq. I am into creating some unit test case to ASP.Net MVC2 project. In one of a controller i have a code,

if( ModelState.IsValid){ ...... ...... }

I tried to mock it in my test method in this way..

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

But the problem is all the time i run the test method ModelState.Isvalid returns false. Problem is I only able to deal with my test project. I am not authorized to make any changes in my ASP.Net mvc2 project. does anyone of you have any idea of doing this? Thankyou.

Upvotes: 2

Views: 267

Answers (1)

Tomas Jansson
Tomas Jansson

Reputation: 23472

What you can do is add a model error to the ModelState, like such:

var controller = new YourController();
controller.ModelState.AddModelError("An error");

with those two lines the IsValid should be false.

Upvotes: 1

Related Questions