Replace EF Core Default Schema in xUnit

67 Views Asked by At

I would like to perform integration testing on my API which connects to an oracle database via EF Core (database-first). Initially, I went with Testcontainers.Oracle but it was running too slow on my machine. Hence, I decided to perform the test using a separate schema. I do not wish to use in-memory database to perform my integration tests.

I have two schemas:

  1. Schema1 (the original schema which the context was scaffolded from)
  2. Schema2 (I would like to create the tables in schema1 here and run my tests)

How do I override the default schema in my web application factory? Currently I have tried to check whether unit test is running in my source project but I would prefer do it inside the test project in case it is overwritten by a new scaffold.

public class MyApiFactory : WebApplicationFactory<IApiMarker>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureTestServices(services =>
        {
            services.RemoveAll(typeof(ApplicationDbContext));
            services.AddDbContext<ApplicationDbContext>(optionsBuilder =>
                optionsBuilder.UseOracle(""));

            // is it possible to change default schema of the model builder?
        });
    }
}

public partial class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public virtual DbSet<MyTable> MyTable{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("Schema1");

#if DEBUG
        if (UnitTestDetector.IsRunningFromXUnit)
        {
            modelBuilder.HasDefaultSchema("Schema2");
        }
#endif

        modelBuilder.Entity<MyTable1>(entity =>
        {
            // some table configuration
        });
    }
}
0

There are 0 best solutions below