I\'ve overridden my controller\'s OnActionExecuting method to set some internal state based on the executing filterContext. How do I test this? The method itself is protected so
I was trying to do this, but I actually wanted to test the outcome of the custom attribute as it applied to the actual controller. In our case we had an authorization attribute that set properties on the controller, the controller then used the properties. Our code looks something like this:
// Create the controller to test
PortalController controller = new PortalController();
var method = typeof(PortalController);
var attribute = method.GetCustomAttributes(typeof(OrganizationContextFilter),true).Cast().SingleOrDefault();
// Set the controller Context with our fake objects on it
controller.ControllerContext = this.GetDefaultControllerMock(controller);
// Execute the Organization Context Filter
var actionDescriptor = new Mock();
var context = Mock.Get(actionDescriptor.Object);
context.Setup(s => s.ControllerDescriptor).Returns(new Mock().Object);
// Use the current controller Context
ActionExecutingContext filterContext = new ActionExecutingContext( controller.ControllerContext, actionDescriptor.Object, new Dictionary() );
attribute.OnActionExecuting(filterContext);
// We have to use this one, because it has the result of the Attribute execution
PortalController pc = filterContext.Controller as PortalController;
ActionResult result = pc.MethodToTest(); // Call the controller that had OnActionExecuting results
The benefit of this is that we actually execute the custom MVC attribute on the controller we are actually testing. This both exercises the custom attribute code and tests the controller in a situation that is more like the "real world".