如何在 Web API ASP.Net 核心中对异常过滤器进行单元测试。不想模拟 onException 方法

Muk*_*tal 4 asp.net-mvc unit-testing moq xunit asp.net-core

如何在 Web API ASP.Net 核心中对异常过滤器进行单元测试。不想模拟 onException 方法。我在单元测试中模拟了如下所示的 ControllerContext 。从 Web API 调用的类库会抛出由异常过滤器捕获的自定义异常,我想对其进行单元测试。今天我收到“值不在预期范围内”错误。

    public static ControllerContext GetMockControllerContext(
        this Controller controller,
        RouteData routeData)
    {

        var actionContext = new ActionContext
        {
            HttpContext = new DefaultHttpContext
            {
                User = controller.GetMockUserContext()
            },
            RouteData = routeData,
            ActionDescriptor = new ControllerActionDescriptor()
        };
        return new ControllerContext(actionContext);
    }
Run Code Online (Sandbox Code Playgroud)

ssm*_*ith 6

我将使用文档中介绍的 TestServer 编写集成测试。它的运行速度与实际的单元测试一样快,但更有价值,因为它将证明您的过滤器在实际的 MVC 上下文/管道中工作。