persistence/Persistence.IntegrationTests/WebAppFactoryFixture.cs

70 lines
2.4 KiB
C#

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Persistence.Database.Model;
using Persistence.Database.Postgres;
using Persistence.API;
using Refit;
using System.Text.Json;
using Persistence.Database.Postgres;
using System.Net.Http.Headers;
using Persistence.Client;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Persistence.IntegrationTests;
public class WebAppFactoryFixture : WebApplicationFactory<Startup>
{
private static readonly JsonSerializerOptions JsonSerializerOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
//Converters = { new ValidationResultConverter() }
};
private static readonly RefitSettings RefitSettings = new(new SystemTextJsonContentSerializer(JsonSerializerOptions));
private readonly string connectionString;
public WebAppFactoryFixture()
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.Tests.json")
.Build();
var dbConnection = configuration.GetSection("DbConnection").Get<DbConnection>()!;
connectionString = dbConnection.GetConnectionString();
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<PersistenceDbContext>));
if (descriptor != null)
services.Remove(descriptor);
services.AddDbContext<PersistenceDbContext>(options =>
options.UseNpgsql(connectionString));
services.RemoveAll<IHttpClientFactory>();
services.AddSingleton<IHttpClientFactory>(provider =>
{
return new TestHttpClientFactory(this);
});
var serviceProvider = services.BuildServiceProvider();
using var scope = serviceProvider.CreateScope();
var scopedServices = scope.ServiceProvider;
var dbContext = scopedServices.GetRequiredService<PersistenceDbContext>();
dbContext.Database.EnsureCreatedAndMigrated();
//dbContext.Deposits.AddRange(Data.Defaults.Deposits);
dbContext.SaveChanges();
});
}
}