首页
/ FastEndpoints项目中的并行测试与TestContainers集成实践

FastEndpoints项目中的并行测试与TestContainers集成实践

2025-06-08 22:48:00作者:明树来

背景与问题分析

在使用FastEndpoints框架进行集成测试时,结合TestContainers创建数据库容器是一个常见需求。然而,当尝试并行执行测试类时,开发者可能会遇到WebApplicationFactory(WAF)缓存导致的数据库连接问题。

FastEndpoints默认会缓存并重用WebApplicationFactory实例,这在大多数场景下能提高测试效率。但当每个测试类需要独立的数据库容器时,这种缓存机制会导致所有测试类共享同一个数据库连接,从而引发冲突。

解决方案探索

方案一:禁用并行执行

最简单的解决方案是在xunit配置中禁用并行测试执行。这种方法虽然能解决问题,但牺牲了测试套件的执行速度,不适合大型项目。

方案二:使用泛型AppFixture

FastEndpoints的WAF缓存键是基于AppFixture的类型信息生成的。通过为每个测试类创建独特的AppFixture类型,可以实现每个测试类拥有独立的WAF实例:

// 泛型AppFixture定义
public class IntegrationTestFixture<T> : AppFixture<Program>
{
    private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .WithDatabase("webapp_template_test")
        .Build();

    // 其他实现...
}

// 在测试类中使用
public class UserTests(IntegrationTestFixture<UserTests> fixture) 
    : TestBase<IntegrationTestFixture<UserTests>>
{
    // 测试方法...
}

public class ProductTests(IntegrationTestFixture<ProductTests> fixture)
    : TestBase<IntegrationTestFixture<ProductTests>>
{
    // 测试方法...
}

这种方法虽然有效,但需要为每个测试类创建独特的泛型实例,增加了代码量。

方案三:使用DisableWafCache特性

从FastEndpoints v5.24.0.11-beta版本开始,提供了更优雅的解决方案。开发者可以通过[DisableWafCache]特性显式禁用WAF缓存:

[DisableWafCache]
public class IntegrationTestFixture : AppFixture<Program>
{
    // 实现...
}

这种方法简单直接,每个测试类都会获得全新的WAF实例,确保数据库容器的隔离性。

最佳实践建议

  1. 性能考量:禁用WAF缓存会增加测试启动时间,建议仅在需要独立数据库容器的测试场景中使用。

  2. 资源管理:确保正确实现TearDownAsync方法,及时释放TestContainers资源。

  3. 数据库设计:考虑为每个测试类使用不同的数据库名称,避免潜在的命名冲突。

  4. 测试策略:将需要独立数据库的测试与可以共享数据库的测试分开组织,平衡测试隔离性和执行效率。

实现示例

以下是完整的实现示例,展示了如何结合TestContainers和FastEndpoints进行集成测试:

[DisableWafCache]
public class IntegrationTestFixture : AppFixture<Program>
{
    private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
        .WithImage("postgres:16-alpine")
        .WithDatabase(Guid.NewGuid().ToString("N")) // 唯一数据库名
        .Build();

    protected override async Task SetupAsync()
    {
        await _postgres.StartAsync();
        
        await using var scope = Services.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        await db.Database.EnsureCreatedAsync();
        // 执行种子数据...
    }

    protected override void ConfigureServices(IServiceCollection services)
    {
        services.RemoveAll<DbContextOptions<AppDbContext>>();
        services.RemoveAll<AppDbContext>();
        
        services.AddDbContext<AppDbContext>(options => 
            options.UseNpgsql(_postgres.GetConnectionString()));
    }

    protected override async Task TearDownAsync()
    {
        await _postgres.DisposeAsync();
    }
}

总结

FastEndpoints提供了灵活的测试基础设施,通过理解其WAF缓存机制,开发者可以根据测试需求选择合适的隔离策略。对于需要完全隔离的数据库测试场景,DisableWafCache特性提供了最简洁的解决方案,而泛型AppFixture则提供了更多控制权。根据项目规模和测试需求,选择最适合的方法可以显著提高测试的可靠性和执行效率。

登录后查看全文
热门项目推荐
相关项目推荐