Take the 2-minute tour ×

How can I test Controller.ViewData.ModelState? I would prefer to do it without any mock framework.

share|improve this question
Be more specific. What are you trying to test it for? –  skb Jan 1 '09 at 23:24

2 Answers 2

up vote 30 down vote accepted

You don't have to use a Mock if you're using the Repository Pattern for your data, of course.

Some examples: http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx

// Test for required "FirstName".

   newCustomer = new Customer
       FirstName = "",
       LastName = "Smith",
       Zip = "34275",    


   // Make sure that our validation found the error!
   Assert.IsTrue(controller.ViewData.ModelState.Count == 1, 
                 "FirstName must be required.");
share|improve this answer
A virtual modifier on Errors would be nice, alas there's an arrange tax, which looks a trifle heavy to me. –  Ed Blackburn Feb 9 '12 at 11:45
IMHO Better solution is to use mvc conveyor. In this way you get more realistic behavior of your controller, you should deliver model validation to it's destiny - attribute validations. Below post is describing this (stackoverflow.com/a/5580363/572612). –  Vladimir Shmidt Aug 3 '12 at 7:11
//public string Name { get; set; }
//public string Description { get; set; }

ProductModelEdit model = new ProductModelEdit() ;
//Init ModelState
var modelBinder = new ModelBindingContext()
    ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(
                      () => model, model.GetType()),
    ValueProvider=new NameValueCollectionValueProvider(
                        new NameValueCollection(), CultureInfo.InvariantCulture)
var binder=new DefaultModelBinder().BindModel(
                 new ControllerContext(),modelBinder );

ViewResult result = (ViewResult)ProductController.CreateProduct(null,model);
Assert.IsTrue(result.ViewData.ModelState["Name"].Errors.Count > 0);
Assert.True(result.ViewData.ModelState["Description"].Errors.Count > 0);
share|improve this answer
I really like this method. As you state, it is far better at testing a model properly that has been decorated with validation attributes. –  stevethethread Feb 28 '13 at 15:01
This is awesome! –  Ian1971 Apr 23 '13 at 12:26
Very handy. I think I generally agree with folks that say that you shouldn't be testing your model properties, as that's a part of the framework, but there are times when it's critical to confirm for all future time that your controller is catching critical errors. –  Ken Smith Dec 12 '13 at 19:22

Your Answer


