.net - 如何在 ASP.NET Web Api 中对操作过滤器进行单元测试?

标签 .net unit-testing asp.net-web-api action-filter

我希望向我的服务添加一个操作过滤器,以处理向响应消息添加链接数据。我发现我需要模拟 HttpActionExecutedContext,但这是一个很难模拟的类,您如何处理 Action Filter 测试?

最佳答案

您可以为HttpActionExecutedContext创建一个假的,如下所示:

public static HttpActionContext CreateActionContext(HttpControllerContext controllerContext = null, HttpActionDescriptor actionDescriptor = null)
{
    HttpControllerContext context = controllerContext ?? ContextUtil.CreateControllerContext();
    HttpActionDescriptor descriptor = actionDescriptor ?? new Mock<HttpActionDescriptor>() { CallBase = true }.Object;
    return new HttpActionContext(context, descriptor);
}

public static HttpActionExecutedContext GetActionExecutedContext(HttpRequestMessage request, HttpResponseMessage response)
{
    HttpActionContext actionContext = CreateActionContext();
    actionContext.ControllerContext.Request = request;
    HttpActionExecutedContext actionExecutedContext = new HttpActionExecutedContext(actionContext, null) { Response = response };
    return actionExecutedContext;
}

我刚刚从 ASP.NET Web API 源代码中复制并粘贴了该代码:ContextUtil类(class)。以下是他们如何测试一些内置过滤器的一些示例:

ActionFilterAttributeTestActionFilterAttribute 的测试类,它是一个抽象类,但您会明白的。

关于.net - 如何在 ASP.NET Web Api 中对操作过滤器进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11848137/

相关文章:

unit-testing - Laravel 测试 - 创建路由的问题

python - 如何更改 Python 中所有模块的日期/时间?

c# - 在初始页面加载时从服务器获取类对象并将其放入 js 对象的好方法是什么?

javascript - 浏览器API : URL class is not recognized in Typescript

.net - linq 等效 SQL 查询 "not in (select query)"

.net - 从 Process 对象获取位数(32 位/64 位)

java - Spring-Boot:Mockito Captor:NullPointerException 和 InvalidUseOfMatchersException

c# - 为什么我的 API 在 XML 节点内返回一个 JSON?

c# - 使用超链接发送邮件的 ASP.NET 应用程序

c# - .NET 框架中的 Span<T> 和流