Skip to content

Instantly share code, notes, and snippets.

@TheBenda
Created July 3, 2024 15:33
Show Gist options
  • Save TheBenda/57298e88f02dfc6a95aa946937b5eb1a to your computer and use it in GitHub Desktop.
Save TheBenda/57298e88f02dfc6a95aa946937b5eb1a to your computer and use it in GitHub Desktop.
How to use AppFixture with PostgreSqlContainer
namespace Solution.IntegrationTests;
public abstract class BaseIntegrationTest : TestBase<PostgresTestcontainer> { }
using Testcontainers.PostgreSql;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.EntityFrameworkCore;
using Solution.Persistence;
namespace Solution.IntegrationTests;
public class PostgresTestcontainerBase : AppFixture<Program>
{
private PostgreSqlContainer _postgreSqlContainer;
protected override async Task PreSetupAsync()
{
_postgreSqlContainer = new PostgreSqlBuilder()
.WithImage("postgres:latest")
.WithDatabase("yourdbname")
.WithUsername("postgres")
.WithPassword("postgres")
.Build();
await _postgreSqlContainer.StartAsync();
}
protected override void ConfigureApp(IWebHostBuilder b)
{
b.ConfigureTestServices(services =>
{
var descriptor = services.SingleOrDefault(s => s.ServiceType == typeof(DbContextOptions<YourDbContext>));
if(descriptor is not null) services.Remove(descriptor);
services.AddDbContext<YourDbContext>(options =>
{
// PersistenceExtension resebles the static class in your Projects for DI which includes the Migrations
options.UseNpgsql(_postgreSqlContainer.GetConnectionString(), npgsqlBuilder =>
npgsqlBuilder.MigrationsAssembly(typeof(PersistenceExtension).Assembly.GetName().Name));
});
}
);
}
protected override async Task SetupAsync()
{
using var scope = Services.CreateScope();
await using var dbContext = scope.ServiceProvider.GetRequiredService<YourDbContext>();
await dbContext.Database.MigrateAsync();
}
}
namespace Solution.IntegrationTests;
public class SomeIntegrationTests(PostgresTestcontainerBase _app) : BaseIntegrationTest
{
[Fact]
public async Task Some_Test()
{
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment