In a custom ActionFilter , I want to check the attributes of the controller action that will be executed. When you run a small test application, when you run the application on the asp.net development server, the following occurs:
public class CustomActionFilterAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { var someAttribute = filterContext.ActionDescriptor .GetCustomAttributes(typeof(SomeAttribute), false) .Cast<SomeAttribute>() .SingleOrDefault(); if (someAttribute == null) { throw new ArgumentException(); }
An action method without SomeAttribute throws a ArgumentException and, conversely, an action method with SomeAttribute does not. So far, so good.
Now I would like to configure some unit tests for ActionFilter, but how can I configure the action method by which the OnActionExecuting method should be run in the unit test? Using the following code does not find SomeAttribute in the action method that will be executed. Is the test installed correctly? Didn't I do something right in the test? To clarify, the test is not completed, but I'm not sure what I missed, so SomeAttribute in OnActionExecuting in the test is null
[TestMethod] public void Controller_With_SomeAttribute() { FakeController fakeController = new FakeController(); ControllerContext controllerContext = new ControllerContext(new Mock<HttpContextBase>().Object, new RouteData(), fakeController); var actionDescriptor = new Mock<ActionDescriptor>(); actionDescriptor.SetupGet(x => x.ActionName).Returns("Action_With_SomeAttribute"); ActionExecutingContext actionExecutingContext = new ActionExecutingContext(controllerContext, actionDescriptor.Object, new RouteValueDictionary()); CustomActionFilterAttribute customActionFilterAttribute = new CustomActionFilterAttribute (); customActionFilterAttribute.OnActionExecuting(actionExecutingContext); } private class FakeController : Controller { [SomeAttribute] ActionResult Action_With_SomeAttribute() { return View(); } }
source share