C#C
C#12mo ago
8 replies
surwren

Seeding DB for Integration Test

I am currently using TestContainers and WebApplicationFactory and am able to successfully setup a basic test which returns successfully. I am following the InProcess Example

I am thinking of improving the way I populate data. Currently I populate in Program.cs

using (var scope = app.Services.CreateScope()) {
    var dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();
    dbContext.Database.Migrate();  
    var seeder = scope.ServiceProvider.GetRequiredService<DatabaseSeeder>();
    seeder.SeedAsync().Wait();
}

app.Run();

public partial class Program { }


public class DatabaseSeeder {
    private readonly AppDbContext _context;
    //... services
    public DatabaseSeeder(AppDbContext context, IUserService userService, ...) {
        //constructor assignment for services
    }
    public async Task SeedAsync()
    {
        if (!_context.Users.Any())
        {
            //seeding logic
        }
    }
}
Was this page helpful?