Last active
November 21, 2024 23:12
-
-
Save vladdedita/c305f8a44b127407f64cfe42403f877c to your computer and use it in GitHub Desktop.
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
public class PostgreSQLExtension implements BeforeAllCallback, AfterAllCallback { | |
private static PostgreSQLContainer<?> postgres; | |
@Override | |
@SneakyThrows | |
public void beforeAll(ExtensionContext context) { | |
// Start the PostgreSQL container | |
postgres = new PostgreSQLContainer<>("postgres:latest") | |
.withDatabaseName("testdb") | |
.withUsername("testuser") | |
.withPassword("testpass"); | |
postgres.start(); | |
initProperties(); | |
initData(); | |
} | |
/** | |
* We would normally use @DynamicPropertySource, but this doesn't work in the case of extensions | |
* as the Spring Context is initialized before the extension is called, resulting in the properties not being set. | |
*/ | |
private static void initProperties() { | |
System.setProperty("spring.datasource.url", postgres.getJdbcUrl()); | |
System.setProperty("spring.datasource.username", postgres.getUsername()); | |
System.setProperty("spring.datasource.password", postgres.getPassword()); | |
System.setProperty("spring.datasource.driver-class-name", "org.postgresql.Driver"); | |
System.setProperty("spring.jpa.database-platform", "org.hibernate.dialect.PostgreSQLDialect"); | |
} | |
private static void initData() throws IOException, InterruptedException { | |
postgres.execInContainer("psql", "-U", "testuser", "-d", "testdb", "-c", "CREATE TABLE public.user (id SERIAL PRIMARY KEY, name TEXT)"); | |
postgres.execInContainer("psql", "-U", "testuser", "-d", "testdb", "-c", "INSERT INTO public.user (name) VALUES ('Alice'), ('Bob')"); | |
} | |
@Override | |
public void afterAll(ExtensionContext context) { | |
// Stop the PostgreSQL container | |
if (postgres != null) { | |
postgres.stop(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment