Testcontainers loss of connection after some tests running Testcontainers loss of connection after some tests running docker docker

Testcontainers loss of connection after some tests running


You want to start container for reuse. Put this to the chain of methods:

.withReuse(true);


According to the documentation:

Containers declared as static fields will be shared between test methods. They will be started only once before any test method is executed and stopped after the last test method has executed. Containers declared as instance fields will be started and stopped for every test method.

So perhaps you're containers are relaunched for every test and get new port numbers?

See: https://www.testcontainers.org/test_framework_integration/junit_5/

We run a setup similar to what you want to accomplish, but are instead using a @ContextConfiguration( initializers = [ in the abstract class with a list of initializers where each container is configured and added to the shared ConfigurableApplicationContext. But your approach seems a lot simpler if you can make it work using only the annotations.


After some research I figured out what is the problem: the context.

When spring runs the first mvc controller test, it starts a single instance of tomcat to all controllers, this means when testcontainers recreate the docker instance for the database (after a new controller start testing) the properties (port, URL..) were not updated because spring will reuse the current instance of tomcat (from the last mvc test)

Solution: mark the context as dirty for each test class, this will make spring recreate the context everytime a new test class starts and this will trigger the dynamicPropertiesRegister to update the properties correctly.

I just had to add this annotation @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) to my AbstractTest