客户ActionFilterAttribute的单元测试失败

时间:2019-12-30 03:41:33

标签: asp.net-mvc unit-testing asp.net-core

该项目是aspnet core 2.1,我使用客户ActionFilterAttribute如下:

public override void OnActionExecuting(ActionExecutingContext context)
        { 
            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;
            if (descriptor != null)
            {
                foreach (var parameter in descriptor.MethodInfo.GetParameters())
                {
                    object args = null;
                    if (context.ActionArguments.ContainsKey(parameter.Name))
                    {
                        args = context.ActionArguments[parameter.Name];
                    }

                    ValidateAttributes(parameter, args, context.ModelState);
                }
            }

            if (!context.ModelState.IsValid)
            {
                context.Result = new BadRequestObjectResult(context.ModelState);
            }
        }

现在我添加一个单元测试代码来测试过滤器,

[TestMethod]
        public void ValidateModelAttributes_SetsResultToBadRequest_IfModelIsInvalid()
        {
            var validationFilter = new ValidateModelStateAttribute();
            var modelState = new ModelStateDictionary();
            modelState.AddModelError("name", "invalid");
            var actionDescriptor = new ActionDescriptor();

            var actionContext = new ActionContext(
                Mock.Of<HttpContext>(),
                Mock.Of<RouteData>(),
                Mock.Of<ActionDescriptor>(),
                modelState
            );

            var actionExecutingContext = new ActionExecutingContext(
                actionContext,
                new List<IFilterMetadata>(),
                new Dictionary<string, object>() { { "1", "1" } },
                Mock.Of<Controller>()
            );

            validationFilter.OnActionExecuting(actionExecutingContext);

            Assert.IsNotNull(actionExecutingContext.Result);
        }

但描述符始终返回null:

var descriptor = context.ActionDescriptor as ControllerActionDescriptor;

您能帮我修复单元测试代码吗?

1 个答案:

答案 0 :(得分:1)

  

,但描述符始终返回null`

那是因为在测试中使用了将是Mock.Of<ActionDescriptor>()的{​​{1}},但是被测对象强制转换为ActionDescriptor,而模拟没有,因此为null。

使用适当的模拟

ControllerActionDescriptor

您仍然需要设置模拟,以便在执行测试时被访问的成员表现出预期的行为