【问题标题】:How to configure testcontainers to leave database container running if a test fails?如果测试失败,如何配置测试容器以使数据库容器保持运行?
【发布时间】:2020-10-24 18:58:52
【问题描述】:

当使用Test Containers时,正常的行为是当测试完成时,由于通过或失败,它会关闭容器。

有没有办法配置测试容器,以便在测试失败时保留数据库容器以帮助调试?

【问题讨论】:

    标签: java testing junit integration-testing testcontainers


    【解决方案1】:

    是的,您可以使用 Testcontainers 的重用功能(处于 alpha 状态)在测试后不关闭容器。

    为此,您需要 Testcontainers >= 1.12.3 并选择使用属性文件 ~/.testcontainers.properties

    testcontainers.reuse.enable=true
    

    接下来,声明要重用的容器:

    static PostgreSQLContainer postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer()
      .withDatabaseName("test")
      .withUsername("duke")
      .withPassword("s3cret")
      .withReuse(true);
    

    并确保不使用 JUnit 4 或 JUnit 5 注释来管理容器的生命周期。而是使用单例容器或在@BeforeEach 中为自己启动它们:

    static final PostgreSQLContainer postgreSQLContainer;

    static {
      postgreSQLContainer = (PostgreSQLContainer) new PostgreSQLContainer()
        .withDatabaseName("test")
        .withUsername("duke")
        .withPassword("s3cret")
        .withReuse(true);
     
      postgreSQLContainer.start();
    }
    

    此功能旨在加快后续测试,因为容器仍将正常运行,但我想这也适合您的用例。

    您可以找到详细指南here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2018-09-02
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多