Sobes.tech
Senior

How to organize a common TestContainer for multiple test classes without stopping between them?

sobes.tech AI

Answer from AI

To use a single shared TestContainer for multiple test classes without stopping it between them, you can apply the Singleton pattern or use JUnit 5 annotations to manage the container's lifecycle.

For example, create a class with the container as a static field and initialize it once:

public class SharedContainer {
    public static final GenericContainer<?> container;

    static {
        container = new GenericContainer<>("postgres:13")
            .withExposedPorts(5432);
        container.start();
    }
}

In your test classes, use this container without stopping it:

public class SomeTest {
    @BeforeAll
    static void setup() {
        // Use SharedContainer.container
        String url = "jdbc:postgresql://" + SharedContainer.container.getHost() + ":" + SharedContainer.container.getFirstMappedPort() + "/test";
        // Initialize connection, etc.
    }
}

You can also use a JUnit 5 Extension with the @TestInstance(Lifecycle.PER_CLASS) annotation and manage the container in methods annotated with @BeforeAll and @AfterAll, so the container starts only once for the entire test suite.

If using Spring Boot, you can create a bean with the container and specify singleton scope so that the container lives for the entire test context.