在 ASP.NET Core 集成测试中使用了 WebApplicationFactory ,并且继承 Startup 实现了 TestStartup
public class UploadControllerTests : IClassFixture<UploadWebAppFactory<TestStartup>>
{
private readonly WebApplicationFactory<TestStartup> _factory;
public ImageUploaderControllerTests(
UploadWebAppFactory<TestStartup> factory)
{
_factory = factory;
factory.ConfigureLogging();
}
//...
}
在运行测试时出现了如下的错误:
System.InvalidOperationException : No method 'public static IWebHostBuilder CreateWebHostBuilder(string[] args)' found on 'AutoGeneratedProgram'. Alternatively, WebApplicationFactory`1 can be extended and 'protected virtual IWebHostBuilder CreateWebHostBuilder()' can be overridden to provide your own IWebHostBuilder instance.
Stack Trace:
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateWebHostBuilder()
如果不使用 TestStartup ,直接使用 Startup 则没问题,请问如何解决?
将 TestStartup 移到 ASP.NET Core 项目中,与 Startup 放在同一个项目,问题解决
相关源代码:
后来发现问题的根源是自己使用 TestStartup 的方法不当,不应该在 UploadWebAppFactory 的泛型类型参数中使用 TestStartup ,而应该在 UploadWebAppFactory 的 CreateServer 方法中使用
public class UploadControllerTests : IClassFixture<UploadWebAppFactory<Startup>>
{
private readonly WebApplicationFactory<Startup> _factory;
public ImageUploaderControllerTests(
UploadWebAppFactory<Startup> factory)
{
_factory = factory;
factory.ConfigureLogging();
}
//...
}
public class UploadWebAppFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override TestServer CreateServer(IWebHostBuilder builder)
{
builder.UseStartup<TestStartup>();
return base.CreateServer(builder);
}
}