views:

88

answers:

1

I have the override below to do a few things with cookies using the FormsIdentity Object. But when I instantiate a controller on my Unit Testing this method is not triggered. Any ideas how to do this?

   protected override void Initialize(System.Web.Routing.RequestContext requestContext)
    {
        base.Initialize(requestContext);

        // Grab the user's login information from FormsAuth
        _userState = new UserState();
        if (this.User.Identity != null && this.User.Identity is FormsIdentity)
            this._userState.FromString(((FormsIdentity)this.User.Identity).Ticket.UserData);

        // have to explicitly add this so Master can see untyped value
        this.UserState = _userState;
        //this.ViewData["ErrorDisplay"] = this.ErrorDisplay;

        // custom views should also add these as properties
    }
+1  A: 

Controller.Initialize(RequestContext) is invoked inside ControllerBase.Execute(RequestContext), which in turn can be invoked by the explicit implementation of IController.Execute(RequestContext), so this code will initialize and execute a controller:

IController controller = new TestController();
controller.Execute(requestContext);

I've analyzed the dependency tree for Initialize() and I can't see any other way of invoking this method without resorting to Reflection. You will need to create the RequestContext passed to Execute() as well, which is easier as it looks like you are using Moq:

var wrapper = new HttpContextWrapper(httpContext);
var requestContext = new RequestContext(wrapper, new RouteData());

This link has helpful details on mocking an HttpContext using Moq.

Sam
Thanks, Sam. I was able to trigger Initialize method, but still getting errors, mocking httpContext is a lot harder than I thought.
Geo
HttpContext is the anti-christ of testability - I try to stay away from it as much as possible, and I'm surprised that Initialize() is so weakly testable as well. Maybe you could look at using a custom model binder or property dependency injection instead of using Initialize() at all?
Sam