【问题标题】:Adding a controller explicitly to Owin self hosted WebAPI将控制器显式添加到 Owin 自托管 WebAPI
【发布时间】:2018-11-22 03:11:01
【问题描述】:

我目前正在做一些单元测试,部分功能是调用 API(它有点太多而且对工作过于敏感,无法在这里完全解释它在做什么......)。 本质上,API 将接收请求,进行一些处理并将该请求转发给相关方。 我需要测试该代码,抽象它是不可行的,因为它已经很好地抽象了,但是我无法删除对 HttpClient 的一些硬依赖(在某个阶段,我将不得不调用它..) .

我一直在使用 Owin TestServer 创建一个内存 webapi 服务器,

在此处查看 Strathweb:https://www.strathweb.com/2013/12/owin-memory-integration-testing/

大卫惠特尼在这里:http://www.davidwhitney.co.uk/Blog/2015/01/07/testing-an-asp-net-webapi-app-in-memory/

和 DontCodeTired:http://dontcodetired.com/blog/post/In-Process-Http-Server-for-Integration-Test-Faking-with-Owin-Katana-and-WebAPI

我遇到的问题是,我创建的用于发出请求的 WebApi 服务器将自动检测项目中的其他 API 并针对该 API 运行请求,而不是使用我的单元测试/模拟控制器。

我怎样才能使用HttpConfiguration 对象,在WebApp.Start<**Startup**>() 类中只使用一个控制器?我的意思是这个类:

internal class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();
        config.EnsureInitialized();
        config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
        app.UseWebApi(config);
    }
}

我不清楚如何解决这个问题,因为所有在线示例都在谈论映射 HTTP 路由,而不是删除/手动添加路由。

如果您有任何问题/批评,请添加评论,我会尽我所能更新问题,我觉得由于工作原因,我可以发布的内容可能会有所限制。

【问题讨论】:

    标签: c# asp.net-web-api owin self-hosting


    【解决方案1】:

    我有一个解决方案,我认为是一个整洁的解决方案..

    基于 Strathweb 的博客:https://www.strathweb.com/2013/08/customizing-controller-discovery-in-asp-net-web-api/

    我已经实现了一个自定义 DefaultAssembliesResolver,它排除了包含导致这些问题的其他 API 控制器的程序集。

    自定义解析器:

    public class MyAssembliesResolver : DefaultAssembliesResolver
    {
        public override ICollection<Assembly> GetAssemblies()
        {
            ICollection<Assembly> baseAssemblies = base.GetAssemblies();
            List<Assembly> assemblies = new List<Assembly>(baseAssemblies.Where(x=>!x.FullName.Contains("<nameOfAssemblyToExclude>")));            
            return assemblies;
        }
    }
    

    然后替换启动类中的默认解析器:

    config.Services.Replace(typeof(IAssembliesResolver), new MyAssembliesResolver());
    

    这使我可以排除额外的生产 ApiController(我正在尝试测试),并且只包括我的 ApiController 用于内存 Owin 管道中的单元测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多