假设我想将依赖于 Spring Boot 2.x 应用程序中的 JPA 数据源的测试代码与 PostgreSQL testcontainer
(用于从测试类中管理 Docker 容器的强大工具,具有一个或多个代码行)。进一步假设我正在 application.properties
中管理端口(包含在 JDBC URL 中),例如
spring.datasource.url=jdbc:postgresql://user-service-postgres:5432/user_service
在集成测试中,我使用以下命令创建测试容器
@Rule
PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer();
在准备方法中,我可以使用
访问我想要为spring.datasource.url
设置的值
postgreSQLContainer.getJdbcUrl()
如何告诉测试中的 Spring Boot 使用该 URL,而不是 application.properties
中指定的 URL。
我想坚持使用我的属性文件,以尽量减少更改,但我很感谢其他方法,包括解释为什么它们是优越的或必要的。
我正在使用 Spring Boot 2.x。
最佳答案
自 Spring Framework 5.2.5 (Spring Boot 2.2.6) 起,此设置现在更加简单,因为我们可以使用 @DynamicPropertySource
注释,而不必编写和注册自定义初始值设定项。
假设您使用 Testcontainers 的 JUnit 5 依赖项,您的测试可能如下所示:
@SpringBootTest
@Testcontainers
class ExampleIntegrationTests {
@Container
static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer();
@DynamicPropertySource
static void dataSourceProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", postgreSQLContainer::getJdbcUrl);
}
}
您可以阅读有关此新功能的更多信息 here 。我还在 dedicated Testcontainers guide 中介绍了不同的应用程序属性设置方式(取决于 Spring Boot 和 JUnit 版本) .
关于java - testcontainer启动后,如何在集成测试中覆盖application.properties中定义的端口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55975798/