如何用最小起订量模拟 ActionExecutingContext

How to mock ActionExecutingContext with moq

我正在尝试为 OnActionExecutionAsync 模拟 ActionExecutingContext

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

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

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

我发现这个 很有用,但它没有解释如何模拟 methodInfoGetCustomAttributes

我最近 运行 遇到了一个试图模拟 ActionDescriptor.FilterDescriptors 的类似问题。由于您使用的是 MethodInfo,因此您需要以与我不同的方式解决它。这对我来说没有最小起订量。它归结为获取 MethodInfo 的实例,无论它是真实方法、具有您要测试的相同属性的假 class / 方法,还是模拟的 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()
            {
            }
        }