我们如何在 Testcontainers R2DBC 中初始化架构?

问题描述

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

我的系统框架也使用 spring boot,通常我使用 ContextConfiguration 初始化程序替换 URL。替换 R2DBC 的 URL 后,有没有办法创建架构?

解决方法

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

  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);
  }
}