【问题标题】:How to mock ActionExecutingContext with moq如何使用 moq 模拟 ActionExecutingContext
【发布时间】:2019-10-06 11:18:34
【问题描述】:

我正在尝试为 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);
}

我发现这个How to mock ActionExecutingContext with Moq? 很有用,但它没有解释如何模拟methodInfoGetCustomAttributes

【问题讨论】:

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


    【解决方案1】:

    我最近在尝试模拟 ActionDescriptor.FilterDescriptors 时遇到了类似的问题。由于您使用的是 MethodInfo,因此您需要解决它的方式与我所做的有所不同。没有起订量,这对我有用。它归结为获取 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()
                {
                }
            }
    

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 1970-01-01
      • 2012-03-18
      • 2010-10-19
      • 2016-09-30
      • 1970-01-01
      • 2020-10-27
      • 2012-06-01
      • 2018-12-27
      相关资源
      最近更新 更多