Skip to content

Support multiple DbContexts in integration tests #123

@jakubfijalkowski

Description

@jakubfijalkowski

Currently, we do this in DbContextsInitializer:

foreach (var ctx in getContexts())
{
    await CreatePolicy.ExecuteAsync(async () =>
    {
        await ctx.Database.EnsureDeletedAsync(); // This is the culprit
        await ctx.Database.EnsureCreatedAsync();
    });
}

Unfortunately, if you add multiple DbContexts, every one loop will delete and re-create the database (with different schema!) because we use single connection string. This makes it unusable in multi-context systems. There is a workaround that just overrides the registered context (in TestOverridesPostModule pattern), like:

public override void ConfigureServices(IServiceCollection services)
{
    var oldCtx = services
        .Where(c =>
            c.ServiceType == typeof(ClientsDbContext) ||
            c.ServiceType == typeof(DbContextPool<ClientsDbContext>) ||
            c.ServiceType == typeof(DbContextPool<ClientsDbContext>.Lease) ||
            c.ServiceType == typeof(DbContextOptions<ClientsDbContext>))
        .ToList();
    foreach (var c in oldCtx)
    {
        services.Remove(c);
    }

    var dbConnStr = Api.Config.ConnectionStrings.Database(config);
    var builder = new SqlConnectionStringBuilder(dbConnStr);
    builder.InitialCatalog += "_clients";
    services.AddDbContext<ClientsDbContext>(options =>
    {
        options.UseSqlServer(builder.ToString(), sqlOpts => sqlOpts.MigrationsAssembly("XYZ.Migrations"));
        options.EnableSensitiveDataLogging();
    });
}

but that is suboptimal.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions