How do I run the Initialize method when trying a Unit Test?

I have an override below to do a few things with cookies using a FormsIdentity object. But when I instantiate the controller in my unit test, this method doesn't get triggered. Any ideas how to do this?

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

        // Grab the user 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
    }

      

+2


source to share


1 answer


Controller.Initialize(RequestContext)

is called internally ControllerBase.Execute(RequestContext)

, which in turn can be called by an explicit implementation IController.Execute(RequestContext)

, so this code will initialize and execute the controller:

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

I've analyzed the dependency tree for Initialize()

, and I don't see any other way to call this method without resorting to Reflection. You will need to create the RequestContext

passed in Execute()

, 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 contains useful information about mocking HttpContext using Moq.

+3


source







All Articles