如何在集成测试项目中替换中间件

Lie*_*ero 8 c# integration-testing mstest asp.net-core

我有启动cs,我在这里注册AuthenticationMiddleware:

public class Startup
{
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        ...
        AddAuthentication(app);
        app.UseMvcWithDefaultRoute();
        app.UseStaticFiles();
    }

    protected virtual void AddAuthentication(IApplicationBuilder app)
    {
        app.UseAuthentication();
    }
}
Run Code Online (Sandbox Code Playgroud)

我用它来测试它:

WebApplicationFactory<Startup>().CreateClient();
Run Code Online (Sandbox Code Playgroud)

题:

我想换成app.UseAuthentication();app.UseMiddleware<TestingAuthenticationMiddleware>(),

我尝试过的:

我想过在我的测试项目中继承Startup:

public class TestStartup : Startup
{
    protected override void AddAuthentication(IApplicationBuilder app)
    {
        app.UseMiddleware<AuthenticatedTestRequestMiddleware>();
    }
}

class TestWebApplicationFactory : WebApplicationFactory<Web.Startup>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder()
            .UseStartup<IntegrationTestProject.TestStartup>();
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为TestStartup在另一个程序集中,它有很多副作用 WebHost.CreateDefaultBuilder()

我越来越:

System.ArgumentException:内容根"C:\ Projects\Liero\myproject\tests\IntegrationTests"不存在.参数名称:contentRootPath

Lie*_*ero 5

看来 WebApplicationFactory 应该使用真正的 Startup 类作为类型参数:

class TestWebApplicationFactory : WebApplicationFactory<Startup>
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder<TestableStartup>(new string[0]);
    }
}
Run Code Online (Sandbox Code Playgroud)