Unit test a controller with custom model binder
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.SetFake开发者_开发知识库ControllerContext();
var param = Customer.Load(30005);
param.EmailAddress = "foo@bar.com";
// 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?
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?
精彩评论