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

标签 asp.net-mvc unit-testing asp.net-core moq xunit

如何在 Web API ASP.Net core 中对异常过滤器进行单元测试。不想模拟 onException 方法。我在单元测试中像下面这样 mock 了 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);
    }

最佳答案

我将使用 TestServer 编写集成测试,如 documentation 中所述。 。它的运行速度与实际的单元测试一样快,但更有值(value),因为它将演示您的过滤器在实际的 MVC 上下文/管道中工作。

关于asp.net-mvc - 如何在 Web API ASP.Net core 中对异常过滤器进行单元测试。不想模拟 onException 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42349405/

相关文章:

c# - asp.net mvc 遗留路由映射

Android Studio Junit 测试包 org.junit 不存在

java - 如何模拟 super 引用(在 super 类上)?

c# - WCF 服务中的模拟 OperationContext.Current.ServiceSecurityContext.WindowsIdentity.Name

c# - 无法读取 dotnet 核心中链接的 appsettings.json 文件中的值

javascript - 如何在 MVC 的 C# 中使用本地 IP 地址扫描客户机的开放端口?

c# - 如何告诉 [Authorize] 属性将基本身份验证与自定义消息处理程序一起使用?

c# - 在 ASP.NET Core 中不需要时如何绕过身份验证中间件

asp.net - 我可以坚持使用 ASP.Net 并从 EF6 迁移到 EF Core 吗?

.net - 并行运行 ASP.Net MVC 2 和 MVC 4 的要求