为什么我不能通过带有Microsoft.Owin.Testing.TestServer的MapWhen使用条件中间件

时间:2018-06-27 10:08:31

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

我正在使用Microsoft.Owin.Testing.TestServer为现有的Web API(net452)构建组件测试。我试图尽可能地模仿API的启动逻辑。使用以下方法初始化测试服务器:

private TestServer InitialiseServer(ApiContext context)
{
    var server = TestServer.Create(app =>
    {
        app.StartupApi(context);
    });

    server.BaseAddress = new Uri("https://localhost:81562");

    return server;
}

StartupApi是扩展方法。这是简化版:

public static IAppBuilder StartupApi(this IAppBuilder app, ApiContext context)
{
    var container = WindsorContainerFactory.CreateWithMocks(context);

    MockApiMiddleware(app, container);

    var configuration =
        new HttpConfiguration { DependencyResolver = new WindsorCastleDependencyResolver(container) };

    App_Start.WebApiConfig.Register(configuration);
    app.UseWebApi(configuration);

    app.OnShuttingDown(() =>
    {
        container?.Dispose();
    });

    return app;
}

您可以看到我正在使用作为ApiContext对象传入的测试模拟来创建Windsor IoC容器,然后在执行更多启动任务之前模拟API的中间件。这是我目前正在苦苦挣扎的MockApiMiddleware领域。

最初,MockApiMiddleware方法如下所示:

private static void MockApiMiddleware(IAppBuilder app, IWindsorContainer container)
{
    app.Use(typeof(SomeCustomMiddleware),
        container.Resolve<ISomeDependency>(),
        container.Resolve<ISomeOtherDependency>());
}

当我运行一个测试,该测试针对该测试服务器向已知端点发出请求时,我可以遍历中间件并查看其正在按预期方式进行处理,并且HTTP响应按预期进行,在这种情况下为200。 / p>

但是,真正的API仅在满足Owin条件时才使用此中间件。我真正想要的是:

private static void MockApiMiddleware(IAppBuilder app, IWindsorContainer container)
{
    app.MapWhen(ctx => true,
        appBuilder =>
        {
            app.Use(typeof(SomeCustomMiddleware),
                container.Resolve<ISomeDependency>(),
                container.Resolve<ISomeOtherDependency>());
        });
}

很明显,一旦我开始执行此操作,true就会变得更有意义,但问题是这行不通!有了这个,测试API总是返回404,其他所有条件都相等。但是,中间件仍在被调用。如果我将true切换为false,则测试再次变为绿色。

中间件本身不是问题。我已经将其简化为使用没有依赖项的中间件,除了await Next.Invoke(context)之外什么也没有做,并且观察到相同的模式。

有人可以解释吗?这是Owin.TestServer不支持的事情,还是我做错了什么?

0 个答案:

没有答案
相关问题