using Infrastructure.Data; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.eShopWeb; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System; using Microsoft.EntityFrameworkCore; using Infrastructure.Identity; namespace FunctionalTests.WebRazorPages { public class CustomWebRazorPagesApplicationFactory : WebApplicationFactory { protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { // Create a new service provider. var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .BuildServiceProvider(); // Add a database context (ApplicationDbContext) using an in-memory // database for testing. services.AddDbContext(options => { options.UseInMemoryDatabase("InMemoryDbForTesting"); options.UseInternalServiceProvider(serviceProvider); }); services.AddDbContext(options => { options.UseInMemoryDatabase("Identity"); options.UseInternalServiceProvider(serviceProvider); }); // Build the service provider. var sp = services.BuildServiceProvider(); // Create a scope to obtain a reference to the database // context (ApplicationDbContext). using (var scope = sp.CreateScope()) { var scopedServices = scope.ServiceProvider; var db = scopedServices.GetRequiredService(); var loggerFactory = scopedServices.GetRequiredService(); var logger = scopedServices .GetRequiredService>>(); // Ensure the database is created. db.Database.EnsureCreated(); try { // Seed the database with test data. CatalogContextSeed.SeedAsync(db, loggerFactory).Wait(); } catch (Exception ex) { logger.LogError(ex, $"An error occurred seeding the " + "database with test messages. Error: {ex.Message}"); } } }); } } }