我已经配置了一个xUnit项目来测试Identity Server实现。我创建了一个TestStartup
类,该类继承了Startup
并覆盖了我的Identity Server实现以进行测试。问题是当我使用自定义TestStartup
调用WebApplicationFactory
时,未映射端点。如果我从自定义Startup
调用WebApplicationFactory
,则将映射我的端点。
Startup.cs
protected readonly IConfiguration _configuration;
protected readonly IWebHostEnvironment _webHostEnvironment;
public Startup(IConfiguration configuration, IWebHostEnvironment environment)
{
_configuration = configuration;
_webHostEnvironment = environment;
}
public virtual void ConfigureServices(IServiceCollection services)
{
///code goes here
ConfigureIdentityServices(services);
}
/// <summary>
/// Split into its own method so we can override for testing
/// </summary>
/// <param name="services"></param>
public virtual void ConfigureIdentityServices(IServiceCollection services)
{
///code goes here
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseRouting();
//app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
TestStartup.cs
public TestStartup(IConfiguration configuration, IWebHostEnvironment environment) : base(configuration, environment)
{
}
public override void ConfigureServices(IServiceCollection services)
{
base.ConfigureServices(services);
}
/// <summary>
/// In memory identity database implementation for testing
/// </summary>
/// <param name="services"></param>
public override void ConfigureIdentityServices(IServiceCollection services)
{
//test implementation
}
public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
base.Configure(app, env);
}
自定义WebApplicationFactory
public class ApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override IWebHostBuilder CreateWebHostBuilder()
{
return WebHost.CreateDefaultBuilder(null).UseEnvironment("Development")
.UseStartup<TStartup>();
}
}
控制器测试类
public class UserControllerTests : IClassFixture<ApplicationFactory<Startup>>
{
private readonly ApplicationFactory<Startup> _factory;
public UserControllerTests(ApplicationFactory<Startup> factory)
{
_factory = factory;
}
[Fact]
public async Task Get_Users()
{
var client = _factory.CreateClient();
var result = await client.GetAsync("/user/users");
result.StatusCode.Should().Be(HttpStatusCode.OK);
}
}
运行控制器测试时,即使注入TestStartup
而不是Startup
,也不会从端点路由返回任何端点,即使我从我的base.Configure(app,env)
班。
答案 0 :(得分:2)
我有完全一样的问题。在我的自定义WebApplicationFactory子类中使用子类化启动会导致没有端点注册,而UseStartup会对其进行注册。 奇怪的是,我有另一个API项目(没有Identity),在其中使用子类化的启动实际上注册了端点。试图注释掉启动时的所有内容,但Identity项目中的services.AddControllers和app.UseRouting / app.UseEndpoints除外,
编辑: 找到了解决方案。显然,services.AddControllers仅在执行程序集中注册路由,而在子类Integrationtest场景中,路由是测试程序集。 通过将所需的控制器添加为应用程序部分,路由系统可以选择路由:
services.AddControllers()
.AddApplicationPart(typeof(<controllername>).Assembly);
一切正常。