我有一个集成测试,为此我定义了一个工厂,在其中启动了一个 Postgres 容器
public class IntegrationTestsWebFactory: WebApplicationFactory<Program>,IAsyncLifetime
{
private readonly PostgreSqlContainer _dbContainer = new PostgreSqlBuilder()
.WithImage("postgres:alpine")
.WithDatabase("animalAllies_tests")
.WithUsername("postgres")
.WithPassword("345890")
.Build();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
Environment.SetEnvironmentVariable("ADMIN__USERNAME", "Admin");
Environment.SetEnvironmentVariable("ADMIN__EMAIL", "[email protected]");
Environment.SetEnvironmentVariable("ADMIN__PASSWORD", "Admin123");
builder.ConfigureTestServices(ConfigureDefaultServices);
}
protected virtual void ConfigureDefaultServices(IServiceCollection services)
{
var writeContext = services.SingleOrDefault(s =>
s.ServiceType == typeof(WriteDbContext));
var readContext = services.SingleOrDefault(s =>
s.ServiceType == typeof(ReadDbContext));
if(writeContext is not null)
services.Remove(writeContext);
if(readContext is not null)
services.Remove(readContext);
var configuration = new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
{ "ConnectionStrings:DefaultConnection", _dbContainer.GetConnectionString() }
}!)
.Build();
services.AddScoped<WriteDbContext>(_ => new WriteDbContext(configuration));
services.AddScoped<IReadDbContext>(_ => new ReadDbContext(configuration));
}
public async Task InitializeAsync()
{
await _dbContainer.StartAsync();
using var scope = Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<WriteDbContext>();
await dbContext.Database.EnsureDeletedAsync();
await dbContext.Database.EnsureCreatedAsync();
}
public new async Task DisposeAsync()
{
await _dbContainer.StopAsync();
await _dbContainer.DisposeAsync();
}
}
有一个基类,我在其中初始化测试的所有依赖项。当我尝试通过已发布的工厂对象创建范围时,会发生错误 System.ObjectDisposedException:无法访问已处置的对象。对象名称:'IServiceProvider'。可能存在什么问题?我在什么阶段可以离开工厂?我尝试调试执行,但是在调试中我没有进入由 IAsyncLifetime 实现的 DisposeAsync。
public class VolunteerTestsBase: IClassFixture<IntegrationTestsWebFactory>, IAsyncLifetime
{
protected readonly IntegrationTestsWebFactory _factory;
protected readonly IServiceScope _scope;
protected readonly WriteDbContext _context;
protected readonly Fixture _fixture;
protected VolunteerTestsBase(IntegrationTestsWebFactory factory)
{
_factory = factory;
_scope = factory.Services.CreateScope();
_context = _scope.ServiceProvider.GetRequiredService<WriteDbContext>();
_fixture = new Fixture();
}
public Task InitializeAsync()
{
return Task.CompletedTask;
}
public Task DisposeAsync()
{
_scope.Dispose();
return Task.CompletedTask;
}
}
课程本身和测试
public class CreateVolunteerTests : VolunteerTestsBase
{
private ICommandHandler<CreateVolunteerCommand, VolunteerId> _sut;
public CreateVolunteerTests(IntegrationTestsWebFactory factory) : base(factory)
{
_sut = _scope.ServiceProvider.GetRequiredService<ICommandHandler<CreateVolunteerCommand, VolunteerId>>();
}
[Fact]
public async Task Create_volunteer()
{
//Arrange
var command = _fixture.CreateVolunteerCommand();
//Act
var result = await _sut.Handle(command, CancellationToken.None);
//Assert
result.IsSuccess.Should().BeTrue();
result.Value.Should().NotBeNull();
var volunteer = await _context.Volunteers.FirstOrDefaultAsync(v => v.Id == result.Value);
volunteer.Should().NotBeNull();
volunteer.Id.Should().Be(result.Value);
}
}