Click here to Skip to main content
12,814,994 members (41,517 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


2 bookmarked
Posted 20 Jul 2013

OnActionExecuting and OnActionExecuted in MVC unit test

, 20 Jul 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Here is a simple example of how to automatically call them when the main controller method is called.

When testing MVC controllers, OnActionExecuted and OnActionExecuting functions are not get called. Here is a simple example of how to automatically call them when the main controller method is called. All you have to do is wrap the controller call into the Invoke() function.

public class MyTest
    public void TestSomething()
        var actionResult = Invoke(() => new MyController().DoSomething());      

    protected static T Invoke<T>(Expression<Func<T>> exp) where T : ActionResult
        var methodCall = (MethodCallExpression) exp.Body;
        var method = methodCall.Method;
        var memberExpression = (MemberExpression)methodCall.Object;

        Expression<Func<Object>> getCallerExpression = 
        Func<Object> getCaller = getCallerExpression.Compile();
        var ctrlr = (Controller)getCaller();

        ControllerDescriptor controllerDescriptor = new ReflectedControllerDescriptor(ctrlr.GetType());
        ActionDescriptor actionDescriptor = 
          new ReflectedActionDescriptor(method, method.Name, controllerDescriptor);

        // OnActionExecuting

        var rc = new RequestContext();
        ctrlr.ControllerContext = new ControllerContext(rc, ctrlr);
        var ctx1 = new ActionExecutingContext(ctrlr.ControllerContext, 
          actionDescriptor, new Dictionary<string, object>());
        MethodInfo onActionExecuting = ctrlr.GetType().GetMethod(
          "OnActionExecuting", BindingFlags.Instance | BindingFlags.NonPublic);
        onActionExecuting.Invoke(ctrlr, new object[] { ctx1 });

        // call controller method

        T result = exp.Compile()();

        // OnActionExecuted

        var ctx2 = new ActionExecutedContext(ctrlr.ControllerContext, 
          actionDescriptor, false, null){Result = result};
        MethodInfo onActionExecuted = ctrlr.GetType().GetMethod(
          "OnActionExecuted", BindingFlags.Instance | BindingFlags.NonPublic);
        onActionExecuted.Invoke(ctrlr, new object[] { ctx2 });

        return (T)ctx2.Result;


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Australia Australia
No Biography provided

You may also be interested in...


Comments and Discussions

-- No messages could be retrieved (timeout) --
Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 20 Jul 2013
Article Copyright 2013 by m_kramar
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid