如何配置测试容器以在测试失败时使数据库容器运行?

时间:2020-07-04 05:46:57

标签: java testing junit integration-testing testcontainers

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

是否可以配置测试容器,以便在测试失败时保留数据库容器以帮助调试?

1 个答案:

答案 0 :(得分:2)

是的,您可以使用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内启动它们:

静态最终PostgreSQLContainer postgreSQLContainer;

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

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

您可以找到详细的指南here