【问题标题】:Is it possible to set SpringBootTest properties on the fly?是否可以即时设置 SpringBootTest 属性?
【发布时间】:2020-05-23 21:58:34
【问题描述】:

我有一个 SpringBoot 应用程序,我试图在 Testcontainers 的帮助下对其进行测试。我有类似的东西:

@SpringBootTest
public class DummyIT {

    @ClassRule
    public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer();

    static {
        postgreSQLContainer.start();
        String url = postgreSQLContainer.getJdbcUrl(); 
    }
}

不幸的是,Testcontainers 使用随机端口,如果我理解正确,我们不应该以任何其他方式使用它,这意味着postgreSQLContainer.getJdbcUrl() 的结果不是确定性的。

此外,我的应用程序从其application.properties 检索数据库 url,我的目标是在运行时第一次使用之前,从postgreSQLContainer.getJdbcUrl() 提供的值中替换该值。有没有可能做到这一点?

感谢您的帮助。

【问题讨论】:

标签: java spring-boot testcontainers


【解决方案1】:

您可以使用Testcontainers JDBC URL support

例如,

@SpringBootTest(
   properties = {
      "spring.datasource.url=jdbc:tc:postgresql:9.6.8://localhost/your-database",
      "spring.datasource.username=dummy-user",
      "spring.datasource.password=dummy-password",
      "spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect",
      "spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver"
})
public class DummyIT {
}

Testcontainers 驱动程序ContainerDatabaseDriver 将使用名为your-database 的数据库创建并启动一个PostgreSQL 服务器9.6.8。

【讨论】:

  • 谢谢,我会在星期一第一件事尝试!
猜你喜欢
  • 1970-01-01
  • 2017-03-23
  • 2011-08-06
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 2012-07-25
  • 2019-10-28
  • 1970-01-01
相关资源
最近更新 更多