Added a JUnit 5 extension to setup postgres

This commit is contained in:
Ali Dehghani
2019-10-27 12:30:41 +03:30
parent ed95ec46ee
commit 3d44723b91
2 changed files with 33 additions and 1 deletions

View File

@@ -0,0 +1,32 @@
package com.baeldung;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.testcontainers.containers.PostgreSQLContainer;
/**
* A JUnit 5 extension responsible for setting up a Postgres instance before all
* tests and tearing it down after them.
*/
public class PostgresExtension implements BeforeAllCallback, AfterAllCallback {
private PostgreSQLContainer<?> postgres;
@Override
public void beforeAll(ExtensionContext context) {
postgres = new PostgreSQLContainer<>("postgres:11.1")
.withDatabaseName("baeldung")
.withUsername("test")
.withExposedPorts(5432)
.withPassword("test");
postgres.start();
System.setProperty("TEST_PG_PORT", postgres.getFirstMappedPort() + "");
}
@Override
public void afterAll(ExtensionContext context) {
postgres.stop();
System.clearProperty("TEST_PG_PORT");
}
}

View File

@@ -1,4 +1,4 @@
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:postgresql://localhost:54320/baeldung
spring.datasource.url=jdbc:postgresql://localhost:${TEST_PG_PORT}/baeldung
spring.datasource.username=test
spring.datasource.password=test