views:

204

answers:

1

In my application I have a custom model binder that I set to the DefaultBinder in the global.asax:

 ModelBinders.Binders.DefaultBinder = new XLDataAnnotationsModelBinder();

When writing unit tests for controllers I need to make sure the controller uses the custom model binder but I don't know how to do this.

My test looks like this:

 [Test]
 public void Details_Post_Action_Fails_To_Change_Email_Address_With_Duplicate()
 {
     // Setup
     var controller = new AccountController();
     controller.SetFakeControllerContext();

     var param = Customer.Load(30005);
     param.EmailAddress = "[email protected]";

     // Test
     var result = controller.Details(param);

     // Assert
     Assert.IsTrue(result is ViewResult);  // will be ViewResult if failed....
     Assert.IsFalse(((ViewResult)result).ViewData.ModelState.IsValid);
 }

With this unit test the controller ends up using the DefaultModelBinder. What can I add in this test to ensure the controller uses the custom model binder?

+2  A: 

Scott Hanselman made a blog post related to this a while ago:

Splitting DateTime - Unit Testing ASP.NET MVC Custom Model Binders

The part that would interest you is at the bottom of the post under "Testing the Custom Model Binder". Basically you instantiate a ModelBindingContext, then instantiate your Modelbinder and call Bind() on your Modelbinder passing in the ModelBindingContext you created (and the controller context if required).

Here is another question at SO that also contains the information you need (even if you're not using Moq):

How to Unit Test a custom ModelBinder using Moq?

Jay
The hanselman link appears to be what I'm looking for so I marked this as the answer. I didn't +1 it because actual answer isn't on stackoverflow (meaning that if hansleman's site went down for some reason this answer has no value).
Sailing Judo