Unit Testing Custom Model Binders in MVC3

In my previous post we have seen a way to do unit testing with Sessions in MVC3 using Custom model binders. In this blog post we are going to see how to do unit test the model binder itself.

One remarkable thing which everybody hails in MVC3 is its extensibility and its testability. You can extend/customize the components in the framework and also you can unit test them with ease.

Before getting into unit testing the custom model binder, Lets have a closer look at the BindModel method

In the BindModel method we are making use of Session property in the HttpContext object which is in turn a property of the ControllerContext object that is passed to the BindModel method as a parameter by the MVC3 framework. In order to unit test this method we need to have to control over the HttpContext property of the ControllerContext and the Session property of the HttpContext.

How to get control over those properties ? Thanks to a constructor of ControllerContext

ControllerContext uses the constructor dependency injection to get rid of the direct dependency on HttpContextBase and we are going to exploit this to do unit testing. Using a mocking framework we can easily create a mock of HttpContetBase and drive the unit test.

The Session property of the HttpContextBase is of type HttpSessionStateBase which can also be mocked.

Here is the complete implementation of Test fixture class which unit test the CartModelBinder class that we have seen in the previous post using the mocking library Moq.