I need to setup a policy in base controller that applies to all controller instance, like below:
public class BaseController : Controller
{
private IPolicy Policy;
public BaseController()
{
this.Policy= new Policy(HttpContext);
}
}
Within the Policy class, I need to do something like:
this.httpContextBase.User.
Questions: (Update)
What is the better way to design the BaseController in terms of using HttpContext and Unit test.
Absolutely no way. You are using the
HttpContextinside the constructor of a controller when this context is still not initialized. Not only that this code cannot be tested but when you run the application it will also crash with NRE. You should never use any HttpContext related stuff in a constructor of a controller.One possibility is to refactor your code and perform this inside the Initialize method:
This being said, that’s not the approach I would recommend. I would recommend you using dependency injection instead of service location which is considered by many as an anti-pattern.
So:
Now, all that’s left is to configure your favourite Dependency Injection framework to inject the correct instance into the constructor. For example with Ninject.Mvc3 this is achieved with a single line of code:
Now you can feel more than free to mock this IPolicy in your unit test without even caring about any HttpContext.
For example let’s suppose that you have the following controller that you want to unit test:
Now, all that you need to do is pick up your favorite mock framework (Rhino Mocks in my case) and do the mocking: