将 asp.net core web api 项目的 Program 改为 top-level statements 后集成测试出现下面的异常
System.InvalidOperationException : The entry point exited without ever building an IHost.
Stack Trace:
at Microsoft.Extensions.Hosting.HostFactoryResolver.HostingListener.CreateHost()
at Microsoft.Extensions.Hosting.HostFactoryResolver.<>c__DisplayClass10_0.<ResolveHostFactory>b__0(String[] args)
at Microsoft.AspNetCore.Mvc.Testing.DeferredHostBuilder.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)
at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient()
对应的集成测试代码
[Collection(ZzkApiTestCollection.Name)]
public class SearchWebApiTests
{
private readonly HttpClient _httpClient;
public SearchWebApiTests(ZzkApiTestFactory factory)
{
_httpClient = factory.CreateClient();
}
[Fact]
public async Task Healthcheck_is_ok()
{
var response = await _httpClient.HeadAsync("/healthz");
response.StatusCode.Should().Be(HttpStatusCode.OK);
}
}
ZzkApiTestFactory 的实现
public class ZzkApiTestFactory : WebApplicationFactory<Program>
{ }
从对应的开源实现代码看,如果异常类型是 HostAbortedException
,就会出现 "The entry point exited without ever building an IHost."
try
{
//...
_hostTcs.TrySetException(new InvalidOperationException("The entry point exited without ever building an IHost."));
}
catch (TargetInvocationException tie) when (tie.InnerException?.GetType().Name == "HostAbortedException")
{
// The host was stopped by our own logic
}
// ...
finally
{
// Signal that the entry point is completed
_entrypointCompleted?.Invoke(exception);
}
是 partial class Program
放错地方引起的, 错放在了 集成测试项目中,应该放在 web api 项目中,在 Program.cs 的尾部添加
public partial class Program
{ }
抛异常处对应的源码 HostFactoryResolver.cs#L246
– dudu 1年前