java 如何在TestContainers中关闭关闭容器?

vuktfyat  于 2023-01-04  发布在  Java
关注(0)|答案(2)|浏览(149)

我有一个IT测试的抽象类:

@RunWith(SpringRunner.class)
@Import(DbUnitConfig.class)
@SpringBootTest(classes = App.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
@DbUnitConfiguration(dataSetLoader = DbUnitDataSetLoader.class)
@TestExecutionListeners({
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class,
    DbUnitTestExecutionListener.class
})
public abstract class AbstractIT {

    @ClassRule
    public static final DockerComposeContainer postgres =
        new DockerComposeContainer(new File("src/test/resources/docker-compose-postgres.yml"))
            .withExposedService("cars-user-postgres-it", 5432);

}

当我只启动IT测试类的一个示例时,它工作正常。
但是当我启动多个测试类时,第一个会完成,其他的会因为关闭postgres而失败
这是来自Container的日志:

Stopping 1ykxuc_postgres-it_1 ... 

Stopping 1ykxucpostgres-it_1 ... done
Removing 1ykxuc_postgres-it_1 ... 

Removing 1ykxuc_cars-user-postgres-it_1 ... done
Removing network 1ykxuc_default

如何告诉TestContainers不要在一个类执行之后停止容器,而是在所有类都执行完之后停止容器?

vsikbqxv

vsikbqxv1#

我找到了这个解决方案作为变通办法。也许有更好的解决方案?

private static final DockerComposeContainer postgres = new DockerComposeContainer(new File("src/test/resources/docker-compose-postgres.yml"))
        .withExposedService("postgres-it", 5432);

    /**
     * static block used to workaround shutting down of container after each test class executed
     * TODO: try to remove this static block and use @ClassRule
     */
    static {
        postgres.starting(Description.EMPTY);
    }

yml文件:

version: "2"
services:
cars-user-postgres-it:
    image: postgres
    ports:
        - 5432:5432
    environment:
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: postgres
        POSTGRES_DB: user
oug3syen

oug3syen2#

现在可以通过在设置容器时设置实验.withReuse(true)来实现:

new GenericContainer<>(IMAGE).withExposedPorts(PORT).withReuse(true);

记住以.start()开始容器,并将testcontainers.reuse.enable=true添加到~/. testcontainers.properties
参考:https://www.testcontainers.org/features/reuse/

相关问题