我有一个基本控制器,我在OnActionExecutionAsync方法中为它设置了一些公共控制器属性,然后在OnActionExecuted方法中设置了一些公共视图模型属性--这很好,但是我现在需要为它编写一些单元测试。不给我..。
我的代码是:
public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
//set some controller properties
await base.OnActionExecutionAsync(context, next);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
//set some other viewmodel properties
base.OnActionExecuted(filterContext);
}我在OnActionExecutionAsync测试中遇到的问题是,当方法完成时,它会自动调用OnActionExecuted方法,当ActionExecutedContext为null时,它会因为ActionExecutedContext为null而崩溃。我假设我需要调用await base.OnActionExecutionAsync(context, next);,而不是简单地调用await next();?要继续使用这个管道,尽管在github中检查了Controller代码,但似乎基实现只在ActionExecutingContext的结果为空基于GitHub的aspnet核心控制器时才调用基于GitHub的aspnet核心控制器--知道如何使测试工作,而不必跳转到OnActionExecuted。
发布于 2017-09-07 14:44:11
你在做整合测试。当事情变得很难测试,这是一个相当清楚的迹象,你已经远远超出了单元测试的界限,应该后退一步,重新评估。如果需要确保某些功能的工作,请创建一个封装该功能的方法,然后对其进行测试。您可以放心地假设OnActionExecutionAsync和这类功能将按预期的方式工作,并调用您的方法,因为该功能已经在MVC代码库中进行了测试。
发布于 2022-05-20 11:32:22
您可以将轻量级委托作为“下一步”项传递。
var httpContext = new DefaultHttpContext();
var actionContext = new ActionContext(_httpContext, new RouteData(), new ActionDescriptor(), new ModelStateDictionary());
var actionExecutingContext = new ActionExecutingContext(actionContext, new List<IFilterMetadata>(), new Dictionary<string, object>(), controller: null);
var executedContext = new ActionExecutedContext(actionContext, new List<IFilterMetadata>(), null);
await actionFilter.OnActionExecutionAsync(actionExecutingContext, () => Task.FromResult(executedContext));https://stackoverflow.com/questions/46098692
复制相似问题