![](/img/trans.png)
[英]Upgrading org.testcontainers from 1.10.6 to 1.15.1 - PostgreSQLContainer.start() dissapears
[英]Is it possible to edit schema and db name of org.testcontainers.containers.PostgreSQLContainer?
我正在使用 TestContainers 的PostgreSQLContainer
來測試 Spring 應用程序,並且我想將數據庫配置為具有特定的架構和數據庫名稱。 默認值為 db_name= test
和 schema= public
。
可以編輯這些嗎? 那么,在哪里以及如何?
我有一個application.properties
文件:
spring.datasource.url=${DB_URL}
spring.datasource.username=${DB_USERNAME}
spring.datasource.password=${DB_PASSWORD}
我的 PostgreSQLContainer start()
方法的實現:
import org.testcontainers.containers.PostgreSQLContainer;
public class DefaultPostgresContainer extends PostgreSQLContainer<DefaultPostgresContainer> {
private static final String IMAGE_VERSION = "postgres:13";
private static DefaultPostgresContainer container;
private DefaultPostgresContainer() {
super(IMAGE_VERSION);
}
public static DefaultPostgresContainer getInstance() {
if (container == null) {
container = new DefaultPostgresContainer().withInitScript("init_postgresql.sql");
}
return container;
}
@Override
public void start() {
super.start();
System.setProperty("DB_URL", container.getJdbcUrl());
System.setProperty("DB_USERNAME", "my_test");
System.setProperty("DB_PASSWORD", "my_test");
}
@Override
public void stop() {
//do nothing, JVM handles shutdown
}
}
正如評論中提到的, withDatabaseName()
方法將為您提供一種設置與默認值不同的名稱的方法。 因此,在您的情況下,您可以簡單地執行以下操作:
public static DefaultPostgresContainer getInstance() {
if (container == null) {
container = new DefaultPostgresContainer()
.withInitScript("init_postgresql.sql")
.withDatabaseName("mydatabase");
}
return container;
}
注釋中也已經給出了使用模式的提示:自定義模式可以通過 JDBC 輕松管理(您必須在使用之前創建它)。
在 JDBC 與PostgreSQLContainer
的連接中,對於 select 自定義模式作為“默認”,您可以執行以下操作:
Properties properties = new Properties();
properties.setProperty("user", psqlContainer.getUsername());
properties.setProperty("password", psqlContainer.getPassword());
properties.setProperty("currentSchema", SCHEMA_NAME); // this sets the "default" schema for queries
final Connection connection = DriverManager.getConnection(psqlContainer.getJdbcUrl(), properties);
如果你想看到它的實際效果,我已經整理了一些簡單的測試用例來展示這里解釋的機制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.