gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:38:22 25 4
gpt4 key购买 nike

我有启动 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();
}
}

我使用以下方法对其进行测试:

WebApplicationFactory<Startup>().CreateClient();

问题:

我想替换 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>();
}
}

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

我得到:

System.ArgumentException: The content root 'C:\Projects\Liero\myproject\tests\IntegrationTests' does not exist. Parameter name: contentRootPath

最佳答案

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

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

关于c# - 如何在集成测试项目中替换中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52136731/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com