I have several test nodes, but I run the container as a singleton.
@ActiveProfiles("test")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ContextConfiguration(initializers = ApplicationTests
.DockerPostgresDataSourceInitializer.class)
public abstract class ApplicationTests {
static PostgreSQLContainer<?> postgresSQLContainer;
static {
postgresSQLContainer = new PostgreSQLContainer<>("postgres:14")
.withUsername("test")
.withPassword("test")
.withInitScript("sql/init.sql")
.withDatabaseName("test")
.withReuse(true);
postgresSQLContainer.start();
}
public static class DockerPostgresDataSourceInitializer
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
String jdbcUrl = "spring.datasource.url=" + postgresSQLContainer.getJdbcUrl();
String username = "spring.datasource.username=" + postgresSQLContainer.getUsername();
String password = "spring.datasource.password=" + postgresSQLContainer.getPassword();
@Override
public void initialize(@NotNull ConfigurableApplicationContext applicationContext) {
TestPropertySourceUtils
.addInlinedPropertiesToEnvironment(applicationContext, jdbcUrl, username, password);
}
}
@Test
void contextLoads() throws SQLException {
ResultSet resultSet = performQuery(postgresSQLContainer);
resultSet.next();
int columnIndex = 1;
int columnAmountExpected = 1;
int result = resultSet.getInt(columnIndex);
assertEquals(columnAmountExpected, result);
Assertions.assertThat(postgresSQLContainer.isRunning()).isTrue();
}
private ResultSet performQuery(@SuppressWarnings("rawtypes") PostgreSQLContainer postgreSQLContainer)
throws SQLException {
String query = "SELECT 1";
String jdbcUrl = postgreSQLContainer.getJdbcUrl();
String username = postgreSQLContainer.getUsername();
String password = postgreSQLContainer.getPassword();
Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
return conn.createStatement().executeQuery(query);
}
}
The singleton container is started only once when the base class is loaded. The container can then be used by all inheriting test classes. At the end of the test suite the Ryuk container that is started by Testcontainers core will take care of stopping the singleton container.
The Ryuk container does not stop the database container. but he completes his work.
Maybe someone has ideas on how to fix it ?