等待容器在testcontainers中启动,其中包含用于自定义PostgreSQL映像的GenericContainer

等待容器在testcontainers中启动,其中包含用于自定义PostgreSQL映像的GenericContainer,postgresql,spring-boot,docker,testcontainers,testcontainers-junit5,Postgresql,Spring Boot,Docker,Testcontainers,Testcontainers Junit5,我正在基于Testcontainers解决方案开发系统/集成测试。我需要使用我们自己的数据库PostgreSQL映像和已经应用的数据库模式 因此,我使用Testcontainers GenericContainer private static final GenericContainer postgresDb = new GenericContainer(POSTGRES_IMAGE).withExposedPorts(5432); 我正在用SpringBoot开发测试,所以出于这个原因,我

我正在基于Testcontainers解决方案开发系统/集成测试。我需要使用我们自己的数据库PostgreSQL映像和已经应用的数据库模式

因此,我使用Testcontainers GenericContainer

private static final GenericContainer postgresDb = new GenericContainer(POSTGRES_IMAGE).withExposedPorts(5432);
我正在用SpringBoot开发测试,所以出于这个原因,我创建了一个抽象类,它将为所有测试保存这个配置

@ActiveProfiles("test")
@SpringBootTest
public abstract class AbstractTests {

    private static final DockerImageName POSTGRES_IMAGE = DockerImageName.parse("docker-name:latest");
    private static final GenericContainer postgresDb;

    static {
        postgresDb = new GenericContainer(POSTGRES_IMAGE)
            .withExposedPorts(5432);
        postgresDb.withStartupTimeout(Duration.ofSeconds(30))
            .start();
    }

    @DynamicPropertySource
    static void properties(DynamicPropertyRegistry registry) throws InterruptedException {
        final String s = "jdbc:postgresql://"+ postgresDb.getHost() +":"+ postgresDb.getMappedPort(5432) + "/test";
        registry.add("spring.datasource.url", () ->s);
    
    }

}
然而,问题是当测试运行时,容器仍然在启动。由于某些原因,使用StartUptimeout(持续时间秒(30))时不起作用

当我在debug at properties方法中停止并给几秒钟时间启动一个容器时,所有测试都正常运行

当测试失败时,我会看到下一个日志:

org.postgresql.util.PSQLException: FATAL: the database system is starting up
如果我把Thread.sleep(…)放进去,它也可以工作,这不是更好的解决方案


等待的正确解决方案是什么?知道容器已准备就绪的正确策略是什么?

我认为答案就在他们的答案中,特别是这一部分:

日志输出等待策略 在某些情况下,容器的日志输出是确定它是否准备就绪的简单方法。例如,我们可以在容器的日志中等待“Ready”消息,如下所示:

公共GenericContainerWithLogWait=新的GenericContainer(DockerImageName.parse(“redis:5.0.3”)) .带有暴露端口(6379) .等待( Wait.forLogMessage(“.*Ready to accept connections.\\n”,1) ); 注意:您需要将消息更改为以下内容:

“*数据库系统已准备好接受连接。*”