我有几个测试节点,但我将容器作为单例运行。
@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);
}
}
单例容器仅在基类加载时启动一次。然后,所有继承的测试类都可以使用该容器。在测试套件结束时,由 Testcontainers 核心启动的 Ryuk 容器将负责停止单例容器。
Ryuk 容器不会停止数据库容器。但他完成了他的工作。
也许有人对如何解决它有想法?
使用时withReuse(true)
并且启用可重用模式后,Ryuk 不会删除容器。这是设计使然的。如果您希望 Ryuk 清洁容器,请不要使用可重用模式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)