Certain parts of ASP.NET MVC can be a real pain to test. Namely Model Binders, Action Filters and anything that relies on some magic “Context” that seems to derive from HttpContext, ControllerContext, RequestContext, etc.
Below, I’ve outlined how I’ve unit tested a Action Filter. You could extrapolate some of this code into a base Test Class, but I’ve left it all in one place so you can see whats going on.
Background
The action filter filters out Employees based upon a “group”. Employee id’s are in a table and if the employee id has a parent id it is part of a group. I want to be able to put this action filter on any action or controller where groups should not be allowed. If the employee is part of a group, I want to change the ViewResult to ContentResult and stuff some html in there for the user to see. Therefore if the user cannot cannot access this screen, they’ll still see the master page, etc, but the view will be some plain text letting them know that they cannot view the page through a group.
Here’s the code:
using System.Web.Mvc; using SharpArch.Core; namespace Agilevent.UI.Web.ActionFilters { public class EmployeeGroupRestrictedActionFilterAttribute : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { // Get Employee Id var employeeId = int.Parse(filterContext.RouteData.GetRequiredString("employeeId")); var employeeInfo = SafeServiceLocator<IEmployeeInfoService>.GetService().GetById(employeeId); if (employeeInfo.IsGroup) { filterContext.Result = new ContentResult {Content = HtmlResultString}; } base.OnActionExecuted(filterContext); } public string HtmlResultString { get { return "This screen is only accessible by selecting a the actual employee. You cannot view it through a group id."; } } } }
The Unit Test
The unit test mocks out the Action Executed Context with the values that I need mocked out. I make sure that the RouteData contains a value that I need and then the Service Locator is set up to return a mock service which will return a mocked out Employee with a known state. Since the employee is a group the test will fall into the ContentResult and we can test from there.
Here’s the code:
using System; using System.Security.Policy; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Microsoft.Practices.ServiceLocation; using Moq; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using StructureMap; using StructureMap.ServiceLocatorAdapter; namespace Agilevent.UnitTests.MVC.ActionFilters { [TestFixture] public class EmployeeGroupRestrictedActionFilterTests { private Container _container; private Mock<IEmployeeInfoService> _employeeInfoService; private EmployeeInfo _employeeInfo; [Test] public void should_not_be_able_to_continue_if_the_employee_id_is_a_group() { // Set up fake employee info as a group _employeeInfo = new EmployeeInfo(); _employeeInfo.IsGroup = true; // Set up employee info service to return the fake employee when called with "123" _employeeInfoService = new Mock<IEmployeeInfoService>(); _employeeInfoService.Setup(b => b.GetById(It.Is<int>(i => i == 123))).Returns(_employeeInfo); // Set up the container & Service Locator _container = new Container(); _container.Configure(x => x.For<IEmployeeInfoService>().Use(_employeeInfoService.Object)); ServiceLocator.SetLocatorProvider(() => new StructureMapServiceLocator(_container)); // Mock out the context to run the action filter. var request = new Mock<HttpRequestBase>(); var httpContext = new Mock<HttpContextBase>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); var routeData = new RouteData(); // routeData.Values.Add("employeeId", "123"); var actionExecutedContext = new Mock<ActionExecutedContext>(); actionExecutedContext.SetupGet(r => r.RouteData).Returns(routeData); actionExecutedContext.SetupGet(c => c.HttpContext).Returns(httpContext.Object); var filter = new EmployeeGroupRestrictedActionFilterAttribute(); filter.OnActionExecuted(actionExecutedContext.Object); // Assert Assert.That(actionExecutedContext.Object.Result, Is.InstanceOfType(typeof(ContentResult))); Assert.That((actionExecutedContext.Object.Result as ContentResult).Content, Is.EqualTo(filter.HtmlResultString)); } } }
I hope that helps someone out there, I know I’ll probably even come back at some point in the future to see how I did it. 🙂 Enjoy.