简体   繁体   中英

How to configure testcontainers to leave database container running if a test fails?

When using Test Containers the normal behavior is that it will shutdown the container when the test is finished due to pass or failure.

Is there a way to configure test containers so that if a test fails the database container is kept around to help with debugging?

Yes, you can use the reuse feature (in alpha state) of Testcontainers to not shutdown the container after the test.

For this to work you need Testcontainers >= 1.12.3 and opt-in with a properties file ~/.testcontainers.properties

testcontainers.reuse.enable=true

Next, declare your container to be reused:

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

and make sure to not use a JUnit 4 or JUnit 5 annotation to manage the lifecycle of your container. Rather use the singleton containers or start them inside @BeforeEach for yourself:

static final PostgreSQLContainer postgreSQLContainer;

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

This feature is rather intended to speed up subsequent tests as the containers will be still up- and running but I guess this also fits your use case.

You can find a detailed guide here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM