如何解决我们如何在 Testcontainers R2DBC 中初始化架构?
目前,我想为我的系统创建一个集成测试。我正在使用 testcontainers 来生成我的临时数据库实例,并使用 R2DBC 数据库使我的系统具有反应性。问题是我不知道如何在 R2DBC testcontainer 实例中创建架构,testcontainers 网页中的 R2DBC support 和 JDBC 支持文档之间存在明显差异。在JDBC中,替换JDBC URL后有创建schema的部分,而在R2DBC中没有提到替换R2DBC URL后的schema创建。我已经尝试并探索了 PostgreSQLR2DBCDatabaseContainer
中的方法,但没有奏效。
我的系统框架也使用 spring boot,通常我使用 ContextConfiguration
初始化程序替换 URL。替换 R2DBC 的 URL 后,有没有办法创建架构?
解决方法
您有以下选择来实现您想要的:
- 使用 init script。
- 使用 init function。
- 将 singleton pattern 与某些迁移工具一起使用,例如 flyway 或 liquibase 等
如果您使用的是 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);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。