与 WebApplicationFactory 的集成测试因 IServiceProvider 的 ObjectDisposeException 失败

The*_*Dev 5 c# integration-testing xunit asp.net-web-api asp.net-core

我有一个简单的健康检查测试,如下所示:

public class HealthCheckEndpointTests : IClassFixture<ItemsApplicationFactory>
{
    private readonly ItemsApplicationFactory _factory;

    public HealthCheckEndpointTests(ItemsApplicationFactory factory)
    {
        _factory = factory;
    }

    public async Task HealthCheck_Test()
    {
       // Arrange
       HttpClient httpClient = _factory.CreateClient();

       // Act 
       string response = await httpClient.GetStringAsync("/health/live");

       // Assert
       Assert.Equal("Healthy", response);
    }
}
Run Code Online (Sandbox Code Playgroud)

我的 ItemsApplicationFactory 如下所示:

public class ItemsApplicationFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureKestrel(options => options.AllowSynchronousIO = true);


        builder.ConfigureServices(services =>
        {
            // remove db context options if exists 
            var dbContextDescriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<ItemsDbContext>));
            if (dbContextDescriptor != null)
                services.Remove(dbContextDescriptor);

            var serviceCollection = new ServiceCollection()
                .AddEntityFrameworkInMemoryDatabase()
                .BuildServiceProvider();

            services.AddDbContext<ItemsDbContext>(mariaDb =>
            {
                mariaDb.UseInMemoryDatabase("template");
                mariaDb.UseInternalServiceProvider(serviceCollection);
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

当我运行测试时,抛出以下异常

System.ObjectDisposedException : Cannot access a disposed object.
Object name: 'IServiceProvider'
Run Code Online (Sandbox Code Playgroud)

我改变了我的测试,看看异常是否是由 ItemsApplicationFactory 或 HttpClient 的初始化引起的。所以测试看起来像这样

public class HealthCheckEndpointTests : IClassFixture<ItemsApplicationFactory>
{
    private readonly ItemsApplicationFactory _factory;

    public HealthCheckEndpointTests(ItemsApplicationFactory factory)
    {
        _factory = factory;
    }

    public async Task HealthCheck_Test()
    {
       // Arrange
       HttpClient httpClient = _factory.CreateClient();

       // Act 
       await Task.Completed();

       // Assert
       Assert.True(true);
    }
}
Run Code Online (Sandbox Code Playgroud)

测试没有抛出任何异常。

为什么_factory.CreateClient();不抛出,却httpClient.GetStringAsync("/health/live")抛出?以及如何解决这个问题?