Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Model binding in ASP.NET MVC 2

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);
like image 804
detroitpro Avatar asked Nov 05 '22 18:11

detroitpro


1 Answers

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.
like image 182
detroitpro Avatar answered Nov 09 '22 12:11

detroitpro