Testing Model binding in ASP.NET MVC 2

1.3k views Asked by At

First; I know that I should not need to test the internals of MVC but I REALLY need a suite a tests around data flowing into our system.

How can I, I hope without mocking all of HTTP context, test that objectA (form collection, dict, collection, object, etc) does or does not conform to objectAModel?

I'd like to not have to instantiate my controller or call the action. I simply want to test if my new object invalidates the modelstate.

I wish I could simply write

var modelState = new ModelBindingContext<objectAModel>().validate(objectA);
2

There are 2 answers

1
detroitpro On

Brad Wilson has an excellent post on DataAnnotations


How Do I Test It?

Using the DataAnnotations attributes for your models moves the validation out of the controller actions and into the model binder, which means your unit tests for your controller actions will be simplified.

When you’re writing tests for this, you need to verify three things:

  1. Is the DataAnnotationsModelBinder registered as the default binder? You’ll only do this once for the whole application, much like the route tests you would write.
  2. Is my model properly decorated with DataAnnotations attributes? You’ll end up writing tests for each validation attribute that you add to your model.
  3. Does my action method properly react when the model state is invalid? You’ll only need to write this once per action method.
0
sean woodward On

Very simply, you can implement a method that pulls the ModelMetadata for your model's type, gets the ModelValidator, and validates the model object.

public bool IsModelValid<T>(T model) where T : class
{
    var metaData = ModelMetadataProviders.Current.GetMetadataForType(() => model, typeof(T));
    var validator = ModelValidator.GetModelValidator(metaData, new ControllerContext());
    var validationResults = validator.Validate(model);
    return 0 == validationResults.Count();
}

By "simply", I mean this does not necessarily take all possible configurations in to consideration, but you can get a basic check on your model's validity.