应用程序尝试连接到 mssql 的真实实例而不是 mssql 测试容器

问题描述 投票:0回答:0

我最近遇到了测试容器,我遇到了 mssql test containre 的问题,

我创建一个 CustomWebApplicationFactory 并启动其中的容器

我还通过覆盖 ConfigureWebHost 方法为数据库添加新配置

但是应用程序无法连接到构建的测试容器,并尝试在我的机器上使用 mssql 服务器的真实实例并获得 用户 sa 登录失败

任何想法将不胜感激

自定义网络工厂代码:

public class CustomWebApplicationFactory<TProgram, TDbContext> : WebApplicationFactory<TProgram>, IAsyncLifetime
{
private readonly MsSqlContainer _mssqlContainer;
private readonly RedisContainer _redisContainer;
private readonly RabbitMqContainer _rabbitMqContainer;

public CustomWebApplicationFactory()
{

    _mssqlContainer = new MsSqlBuilder().Build();
    _redisContainer = new RedisBuilder().WithImage("redis:latest").Build();
    _rabbitMqContainer = new RabbitMqBuilder().WithImage("rabbitmq:3-management").Build();
}

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
    builder.ConfigureTestServices(services =>
    {
        services.RemoveAll<IContext>();
        services.RemoveAll<Context>();

        services.AddDbContext<Context>(options =>
        {
            options.UseSqlServer(_mssqlContainer.GetConnectionString(),
                sqlOptions =>
                {
                    sqlOptions.EnableRetryOnFailure(
                        10,
                        TimeSpan.FromSeconds(30),
                        null);
                });
            options.EnableSensitiveDataLogging();
        });

        var sp = services.BuildServiceProvider();

        using var scope = sp.CreateScope();
        var scopedServices = scope.ServiceProvider;
        var db = scopedServices.GetRequiredService<Context>();


        // error throws here : Login Failed for user sa.
        db.Database.EnsureCreated();
        db.Database.Migrate();

        services.AddScoped<IContext>(provider => provider.GetService<Context>()!);
    });
}

public async Task InitializeAsync()
{
    await Task.WhenAll(
        _mssqlContainer.StartAsync(),
        _redisContainer.StartAsync(),
        _rabbitMqContainer.StartAsync()
        );
}
public new async Task DisposeAsync()
{
    await _mssqlContainer.StopAsync();
    await _redisContainer.StopAsync();
    await _rabbitMqContainer.StopAsync();
}

}

.net sql-server xunit testcontainers
© www.soinside.com 2019 - 2024. All rights reserved.