如何在集成测试项目中替换中间件 [英] How to replace Middleware in integration tests project
问题描述
我有一个启动CS,我在其中注册AuthenticationMiddleware是这样的:
I have startup cs where I register AuthenticationMiddleware like this:
public class Startup
{
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
AddAuthentication(app);
app.UseMvcWithDefaultRoute();
app.UseStaticFiles();
}
protected virtual void AddAuthentication(IApplicationBuilder app)
{
app.UseAuthentication();
}
}
我用以下方法进行测试:
and I test it using:
WebApplicationFactory<Startup>().CreateClient();
问题:
我想用app.UseMiddleware<TestingAuthenticationMiddleware>()
替换app.UseAuthentication();
我在我的测试项目中考虑过从Startup继承:
I thought about inheriting from Startup in my test project:
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()
but this does not work, since TestStartup is in another assembly, which has a lot of side effects on WebHost.CreateDefaultBuilder()
我得到了:
System.ArgumentException:内容根 'C:\ Projects \ Liero \ myproject \ tests \ IntegrationTests'不存在. 参数名称:contentRootPath
System.ArgumentException: The content root 'C:\Projects\Liero\myproject\tests\IntegrationTests' does not exist. Parameter name: contentRootPath
推荐答案
似乎WebApplicationFactory应该使用真实的Startup类作为类型参数:
It seems that WebApplicationFactory should use the real Startup class as the type argument:
class TestWebApplicationFactory : WebApplicationFactory<Startup>
{
protected override IWebHostBuilder CreateWebHostBuilder()
{
return WebHost.CreateDefaultBuilder<TestableStartup>(new string[0]);
}
}
这篇关于如何在集成测试项目中替换中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!