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

2

16

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?

Cenesthesia answered 4/7, 2020 at 5:46 Comment(0)
A
20

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.

Alienate answered 4/7, 2020 at 16:35 Comment(0)
C
2

The awesome feature for reusable containers also works with JDBC urls, by just adding the query parameter TC_REUSABLE=true, like:

spring.datasource.url=jdbc:tc:mysql:8://localhost:3306/dbname?TC_REUSABLE=true

You still need to enable the feature by adding the entry testcontainers.reuse.enable=true to ~/.testcontainers.properties.

Cinderella answered 12/1 at 22:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.