首页 新闻 会员 周边 捐助

.NET: 集成测试报错 "The entry point exited without ever building an IHost"

0
悬赏园豆:30 [已解决问题] 解决于 2023-02-14 12:28

将 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);
}
dudu的主页 dudu | 高人七级 | 园豆:30948
提问于:2023-02-14 09:38

抛异常处对应的源码 HostFactoryResolver.cs#L246

dudu 1年前
< >
分享
最佳答案
0

partial class Program 放错地方引起的, 错放在了 集成测试项目中,应该放在 web api 项目中,在 Program.cs 的尾部添加

public partial class Program
{ }
dudu | 高人七级 |园豆:30948 | 2023-02-14 12:11
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册