如何使用Moq模拟ActionExecutingContext

时间:2019-05-20 05:49:50

标签: c# asp.net asp.net-mvc unit-testing moq

我正在为ActionExecutingContext嘲笑OnActionExecutionAsync

我需要为以下代码编写单元测试用例。

public async Task OnActionExecutionAsync(
           ActionExecutingContext context,
           ActionExecutionDelegate next)
{
    var controllerInfo = actionExecutingcontext.ActionDescriptor as ControllerActionDescriptor;

    MyCustomAttribute[] myCustomAttribute = (MyCustomAttribute[])controllerInfo.MethodInfo.GetCustomAttributes(typeof(MyCustomAttribute), inherit: true);
}

我发现此How to mock ActionExecutingContext with Moq?很有用,但没有说明如何模拟methodInfoGetCustomAttributes

1 个答案:

答案 0 :(得分:1)

我最近在尝试模拟ActionDescriptor.FilterDescriptors时遇到了类似的问题。由于您使用的是MethodInfo,因此您需要解决的方法与我稍有不同。没有Moq,这对我有用。归结为获取MethodInfo实例,无论它是真正的方法,具有要测试的相同属性的伪类/方法,还是模拟的MethodInfo。

        private static ActionExecutingContext CreateActionExecutingContextTest()
        {
            Type t = typeof(TestClass);

            var activator = new ViewDataDictionaryControllerPropertyActivator(new EmptyModelMetadataProvider());
            var actionContext = new ActionContext(
                new DefaultHttpContext(),
                new RouteData(),
                new ControllerActionDescriptor()
                {
                    // Either Mock MethodInfo, feed in a fake class that has the attribute you want to test, or just feed in
                    MethodInfo = t.GetMethod(nameof(TestClass.TestMethod))
                });
            var controllerContext = new ControllerContext(actionContext);
            var controller = new TestController()
            {
                ControllerContext = controllerContext
            };

            activator.Activate(controllerContext, controller);

            return new ActionExecutingContext(
                actionContext,
                new List<IFilterMetadata>(),
                new Dictionary<string, object>(),
                controller);
        }

        public class TestClass
        {
            [MyCustomAttribute]
            public void TestMethod()
            {
            }
        }