重构 asp.net core web 项目将 Program + Startup 改为单 Program 之后,运行集成测试报错:
A public method named 'Configuretest' or 'Configure' could not be found in the 'Program' type
异常发生在通过 WebApplicationFactory 创建 HttpClient 的时候,以下是异常堆栈信息
System.InvalidOperationException : A public method named 'Configuretest' or 'Configure' could not be found in the 'Program' type.
Stack Trace:
at Microsoft.AspNetCore.Hosting.StartupLoader.FindMethod(Type startupType, String methodName, String environmentName, Type returnType, Boolean required)
at Microsoft.AspNetCore.Hosting.StartupLoader.FindConfigureDelegate(Type startupType, String environmentName)
at Microsoft.AspNetCore.Hosting.GenericWebHostBuilder.UseStartup(Type startupType, HostBuilderContext context, IServiceCollection services, Object instance)
at Microsoft.Extensions.Hosting.HostBuilder.InitializeServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateHost(IHostBuilder builder)
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.ConfigureHostBuilder(IHostBuilder hostBuilder)
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.EnsureServer()
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers)
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers)
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options)
是下面的代码中 UseStartup<Program>
引起的,之前是 UseStartup<Startup>
,在将集成测试中的 Startup 替换为 Program 时一起被替换了,现在整个 CreateHostBuilder() 方法都可以删除了
public class BlogWebApplicationFactory<TStartup>
: WebApplicationFactory<TStartup>
where TStartup : class
{
protected override IHostBuilder CreateHostBuilder()
{
return Host.CreateDefaultBuilder()
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Program>();
});
}
}