Created
July 3, 2024 15:33
-
-
Save TheBenda/57298e88f02dfc6a95aa946937b5eb1a to your computer and use it in GitHub Desktop.
How to use AppFixture with PostgreSqlContainer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Solution.IntegrationTests; | |
public abstract class BaseIntegrationTest : TestBase<PostgresTestcontainer> { } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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