Загрузка данных


using Dapper;
using IntegrationTestLearning.Tests.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
using Xunit;

namespace IntegrationTestLearning.Tests.Integration;

public class SettlementControllerTests(SettlementApiFactory factory) : IClassFixture<SettlementApiFactory>
{
    [Fact]
    public async Task GetSettlement_ReturnsOk_WhenSettlementExists()
    {
        await using var connection = new NpgsqlConnection(factory.Services.GetRequiredService<IConfiguration>()["ConnectionStrings:pgsql"]);
        await connection.OpenAsync();

        var tableName = await connection.ExecuteScalarAsync<string>(
            "SELECT table_name FROM information_schema.tables WHERE table_name = 'Settlement'");

        Assert.Equal("Settlement", tableName);

        await connection.ExecuteAsync("INSERT INTO \"Settlement\" (id, nameobject) VALUES (777, 'Grodno')");

        var client = factory.CreateClient();

        var response = await client.GetAsync("/api/Settlement?code=777");

        response.EnsureSuccessStatusCode();

        var responseBody = await response.Content.ReadAsStringAsync();

        Assert.Equal("Grodno", responseBody);
    }
}

using FluentMigrator.Runner;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Testcontainers.PostgreSql;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

namespace IntegrationTestLearning.Tests.Infrastructure;

public class SettlementApiFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
    private readonly PostgreSqlContainer _dbContainer = new PostgreSqlBuilder("postgres:18-alpine").Build();

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.UseSetting("ConnectionStrings:pgsql", _dbContainer.GetConnectionString());
    }

    public async Task InitializeAsync()
    {
        await _dbContainer.StartAsync();
        RunMigrations(_dbContainer.GetConnectionString());
    }

    async Task IAsyncLifetime.DisposeAsync() => await _dbContainer.StopAsync();

    private static void RunMigrations(string connectionString)
    {
        var serviceProvider = new ServiceCollection()
            .AddFluentMigratorCore()
            .ConfigureRunner(rb => rb
                .AddPostgres()
                .WithGlobalConnectionString(connectionString)
                .ScanIn(typeof(Program).Assembly).For.Migrations())
            .AddLogging(lb => lb.AddFluentMigratorConsole())
            .BuildServiceProvider(false);

        using var scope = serviceProvider.CreateScope();
        scope.ServiceProvider.GetRequiredService<IMigrationRunner>().MigrateUp();
    }
}