DD.WellWorkover.Cloud/AsbCloudWebApi.IntegrationTests/WebAppFactoryFixture.cs

55 lines
1.6 KiB
C#

using AsbCloudDb;
using AsbCloudDb.Model;
using AsbCloudWebApi.IntegrationTests.TestFakers;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace AsbCloudWebApi.IntegrationTests;
public class WebAppFactoryFixture : WebApplicationFactory<Startup>,
IAsyncLifetime
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var connectionString = configuration.GetConnectionString("TestConnection");
builder.ConfigureServices(services =>
{
var descriptor = services.FirstOrDefault(d => d.ServiceType == typeof(DbContextOptions<AsbCloudDbContext>));
if (descriptor is not null)
services.Remove(descriptor);
services.AddDbContext<AsbCloudDbContext>(options =>
options.UseNpgsql(connectionString));
});
}
public async Task InitializeAsync()
{
using var scope = Services.CreateScope();
var scopedServices = scope.ServiceProvider;
var dbContext = scopedServices.GetRequiredService<AsbCloudDbContext>();
dbContext.Database.EnsureCreatedAndMigrated();
dbContext.Deposits.AddRange(DepositTestFaker.GetDeposits(15));
await dbContext.SaveChangesAsync();
}
public new async Task DisposeAsync()
{
using var scope = Services.CreateScope();
var scopedServices = scope.ServiceProvider;
var dbContext = scopedServices.GetRequiredService<AsbCloudDbContext>();
await dbContext.Database.EnsureDeletedAsync();
}
}