【问题标题】:how to mock ActionExecutingContext and ActionExecutionDelegate to unit test "OnActionExecutionAsync" method using MOQ framework如何模拟 ActionExecutingContext 和 ActionExecutionDelegate 以使用 MOQ 框架对“OnActionExecutionAsync”方法进行单元测试
【发布时间】:2020-01-22 10:38:21
【问题描述】:

我需要为以下方法模拟 ActionExecutingContextActionExecutionDelegate

public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
}

【问题讨论】:

    标签: c# asp.net-core .net-core moq asp.net-core-webapi


    【解决方案1】:

    可以使用现有类型创建上下文和委托,以避免模拟实例所需的大量设置。

    例如

    //Arrange
    var controller = new SubjectControllerUnderTest(...);
    
    var httpContext = new DefaultHttpContext();
    
    var actionContext = new ActionContext {
        HttpContext = httpContext,
        RouteData = new RouteData(),
        ActionDescriptor = new ActionDescriptor(),
    };
    var metadata = new List<IFilterMetadata>();
    
    var context = new ActionExecutingContext(
        actionContext,
        metadata,
        new Dictionary<string, object>(),
        controller); 
    
    ActionExecutionDelegate next = () => {
        var ctx = new ActionExecutedContext (actionContext, metadata, controller);
        return Task.FromResult(ctx);
    };
    
    //Act
    await controller.OnActionExecutionAsync(context, next);
    
    //...
    

    【讨论】:

    • 我收到下一个变量不能为空的错误。
    • 仍然出现错误,“无法将 void 分配给隐式类型变量”
    猜你喜欢
    • 1970-01-01
    • 2018-03-29
    • 2012-10-19
    • 2019-10-06
    • 2012-06-01
    • 2016-08-06
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多