Testcontainers 在 Spring boot 项目中启动两个容器而不是一个

jel*_*jel 5 java flyway spring-boot junit5 testcontainers

我将 Testcontainers 1.15.3 与 Spring Boot 2.4 和 Junit5 一起使用。当我运行测试时, testcontainers 启动第一个容器并执行 Flyway 脚本,然后停止第一个容器。立即启动第二个容器(不启动 Flyway 脚本)。我的测试失败,因为第二个容器不包含数据。

抽象类:

@ExtendWith({RestDocumentationExtension.class, SpringExtension.class})
@TestPropertySource(locations = "classpath:application-test.properties")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public abstract class AbstractIntegrationTest {
//...
}
Run Code Online (Sandbox Code Playgroud)

测试类:

class ClassTest extends AbstractIntegrationTest{
    
    @Test
    void getById () throws Exception {
    //...
    }

}
Run Code Online (Sandbox Code Playgroud)

用于测试的属性文件(jdbc url 包含 jdbc: tc来启动 testcontainer):

spring.flyway.locations = classpath:database/structure,classpath:database/data
spring.datasource.url=jdbc:tc:postgresql:13.3:///databasename?TC_INITSCRIPT=file:src/test/resources/database/dataset/add_user.sql
Run Code Online (Sandbox Code Playgroud)

启动测试后的日志:

...
...
2021-06-21 12:56:52 [main] INFO   [postgres:13.3] - Creating container for image: postgres:13.3
2021-06-21 12:56:52 [main] INFO   [postgres:13.3] - Starting container with ID: 6a41054e8ec0f9045f8db9e945134234458a0e60b6157618f6f139cdf77d0cc4
2021-06-21 12:56:52 [main] INFO   [postgres:13.3] - Container postgres:13.3 is starting: 6a41054e8ec0f9045f8db9e945134234458a0e60b6157618f6f139cdf77d0cc4
...
...
2021-06-21 12:56:53 [main] INFO  o.f.core.internal.command.DbMigrate - Migrating schema "public" to version "1.1.001 - init structure"
...
...
2021-06-21 12:56:55 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
2021-06-21 12:56:55 [main] INFO   [postgres:13.3] - Creating container for image: postgres:13.3
2021-06-21 12:56:55 [main] INFO   [postgres:13.3] - Starting container with ID: f02fccb0706f047918d849f897ce52bf41870a53821663b21212760c779db05f
2021-06-21 12:56:55 [main] INFO   [postgres:13.3] - Container postgres:13.3 is starting: f02fccb0706f047918d849f897ce52bf41870a53821663b21212760c779db05f
Run Code Online (Sandbox Code Playgroud)

正如我们在上面的日志中看到的,创建了两个容器。

你能帮我解决这个问题吗?

谢谢。

jel*_*jel 2

我找到了适合我的情况的解决方案:删除 Flyway 用户和密码属性以仅使用 spring 属性。这些属性的重复导致了数据源的双重启动。

spring:
  flyway:
    locations: [ classpath:flyway-scripts ]
    user: xxx
    password: xxx
  datasource:
    url: jdbc:postgresql://localhost:5432/postgres
    username: xxx
    password: xxx
Run Code Online (Sandbox Code Playgroud)

spring:
  flyway:
    locations: [ classpath:flyway-scripts ]
  datasource:
    url: jdbc:postgresql://localhost:5432/postgres
    username: xxx
    password: xxx
Run Code Online (Sandbox Code Playgroud)