如何使用 MOQ 框架模拟 ActionExecutingContext 和 ActionExecutionDelegate 以单元测试“OnActionExecutionAsync”方法

Joh*_*ave 3 c# moq .net-core asp.net-core asp.net-core-webapi

我需要模拟ActionExecutingContext以下ActionExecutionDelegate方法:

public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
{
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 11

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

例如

//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);

//...
Run Code Online (Sandbox Code Playgroud)