【问题标题】:How do we initialize schema in Testcontainers R2DBC?我们如何在 Testcontainers R2DBC 中初始化模式?
【发布时间】:2021-10-05 19:22:09
【问题描述】:

目前,我想为我的系统创建一个集成测试。我正在使用 testcontainers 来生成我的临时数据库实例,并使用 R2DBC 数据库使我的系统反应。问题是我不知道如何在 R2DBC testcontainer 实例中创建模式,testcontainers 网页中R2DBC supportJDBC 支持之间的文档存在明显差异。在 JDBC 中,我们替换 JDBC URL 后有创建 schema 的部分,而在 R2DBC 中,在我们替换 R2DBC URL 后没有提及创建 schema。我试过探索PostgreSQLR2DBCDatabaseContainer中的方法,但是没用。

我们的系统框架也使用spring boot,通常我使用ContextConfiguration初始化器替换URL。替换 R2DBC 的 URL 后有什么方法可以创建架构?

【问题讨论】:

    标签: postgresql spring-boot integration-testing testcontainers r2dbc


    【解决方案1】:

    您有以下选择来实现您想要的:

    1. 使用init script
    2. 使用init function
    3. singleton pattern与一些迁移工具一起使用,例如flywayliquibase等。

    如果您使用的是Spring Boot,这里有一篇文章展示了它与单例模式的用法:https://rieckpil.de/reuse-containers-with-testcontainers-for-fast-integration-tests/

    对于singleton container approach,您应该执行类似的操作:

    public abstract class PostgresTestContainer {
               
      private final PostgreSQLContainer<?> postgresContainer =
                             new PostgreSQLContainer<>("postgres:13.3-alpine")
                                     .withDatabaseName("foo")
                                     .withUsername("foo")
                                     .withPassword("secret");
    
      static {
        postgresContainer.start();
      }
    
      @DynamicPropertySource
      private static void setDatasourceProperties(DynamicPropertyRegistry registry) {
    
        // JDBC DataSource Example
        registry.add("spring.datasource.url", postgresContainer::getJdbcUrl);
        registry.add("spring.datasource.password", postgresContainer::getPassword);
        registry.add("spring.datasource.username", postgresContainer::getUsername);
    
        // R2DBC DataSource Example
        registry.add("spring.r2dbc.url", () ->
                format("r2dbc:pool:postgresql://%s:%d/%s",
                            postgresContainer.getHost(),
                            postgresContainer.getFirstMappedPort(),
                            postgresContainer.getDatabaseName()));
        registry.add("spring.r2dbc.username", postgresContainer::getUsername);
        registry.add("spring.r2dbc.password", postgresContainer::getPassword);
      }
    }
    

    【讨论】:

    • 据我所见,数据源 url 被 jdbc url 替换。如果主属性使用r2dbc url,会不会报错?
    • 我更新了代码示例以包括 R2DBC 连接以进行澄清。请参阅上方R2DBC DataSource Example 新部分。
    猜你喜欢
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多