gpt4 book ai didi

java - 使用自定义容器作为 TestContainer 的数据库

转载 作者:行者123 更新时间:2023-12-02 01:07:54 24 4
gpt4 key购买 nike

我正在尝试使用 TestContainer 进行 Spring Boot 应用程序的集成测试。

此类应用程序的数据库驻留在自定义 PostgreSQL Docker 镜像中。

在集成测试中,ApplicationContext 通过 MockMvc 启动,容器通过类似的方式启动

public class ITMyServiceTest {

@Autowired
private WebApplicationContext wac;

private MockMvc mockMvc;

@Rule
public PostgreSQLContainer testPostgres = new PostgreSQLContainer("my-custom-database-image")
.withDatabaseName("my_db")
.withUsername("my_name")
.withPassword("my_pwd");

@Test
public void shouldDoSomething() throws Exception {
this.mockMvc.perform(get("/api/do/something")).andDo(print());
}

现在发生的情况是容器已启动,但应用程序上下文并未引用它。

我无法在 .properties 中使用 JDBC URL 方案(例如 spring.datasource.url=jdbc:tc:postgresql://localhost/my_db)文件因为:

  • 如果我指定 postgresql 作为服务器,它将启动另一个服务器,并且上下文将使用它

  • 如果我指定容器的名称(或其他所有内容),测试将正确引发 java.lang.IllegalArgumentException,因为它不是已知的数据库类型。

如何设置 Spring 的应用程序上下文来引用我的容器?

最佳答案

您可能可以拥有不同的application.properties,例如application-it.properties,并将集成测试特定的配置属性定义为 - @TestPropertySource(locations = { "classpath:application-it.properties"} 或在集成测试期间激活不同的配置文件,例如 -@ActiveProfiles(AppConstants.INTEGRATIONTEST)

所以我猜您想将应用程序的数据库端口设置为随机生成的数据库端口。如果是这种情况,那么可以首先公开端口:

public static PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer("my-custom-database-image")
.withDatabaseName("my_db")
.withUsername("my_name")
.withPassword("my_pwd")
.withExposedPorts(5432);

接下来,当您设置 spring.datasource.url 时,您可以设置从 postgresql 容器随机生成的端口(映射到公开的端口),如何在应用程序属性中设置动态值如 this blog post 所示

关于java - 使用自定义容器作为 TestContainer 的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57713258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com