jeudi 31 octobre 2019

How to create separate in memory database for each test?

I'm writing test with xunit on .NET Core 3.0 and i have problem with in memory database. I need separate database for each test but now i create single database which causes problems, but i have no idea how to create new database for each test.

    public class AccountAdminTest :
        IClassFixture<CustomWebApplicationFactory<Startup>>
        {
            private readonly HttpClient _client;
            private IServiceScopeFactory scopeFactory;
            private readonly CustomWebApplicationFactory<Startup> _factory;
            private ApplicationDbContext _context;

            public AccountAdminTest(CustomWebApplicationFactory<Startup> factory)
            {
                _factory = factory;
                _client = _factory.CreateClient(new WebApplicationFactoryClientOptions
                {
                    AllowAutoRedirect = true,
                    BaseAddress = new Uri("https://localhost:44444")
                });

                scopeFactory = _factory.Services.GetService<IServiceScopeFactory>();
                var scope = scopeFactory.CreateScope();
                _context = scope.ServiceProvider.GetService<ApplicationDbContext>();
            }
        }
    public class CustomWebApplicationFactory<TStartup>
     : WebApplicationFactory<TStartup> where TStartup : class
    {
        protected override void ConfigureWebHost(IWebHostBuilder builder)
        {
            builder.ConfigureTestServices(services =>
            {
                var descriptor = services.SingleOrDefault(
                    d => d.ServiceType ==
                        typeof(DbContextOptions<ApplicationDbContext>));

                if (descriptor != null)
                {
                    services.Remove(descriptor);
                }

                services.AddDbContext<ApplicationDbContext>((options, context) =>
                {
                    context.UseInMemoryDatabase("IdentityDatabase");
                });
            });
        }
    }

Aucun commentaire:

Enregistrer un commentaire