79479929

Date: 2025-03-02 23:55:38
Score: 0.5
Natty:
Report link

In my case, I had the postgres variable annotated with @Container which makes the container die after each @Test - reference. Note that Spring will try to reuse the same application context for different tests, so having the @Container annotation would result in the application context referencing the working container in the first test, then after that the next test will try to reference the container but it has already stopped. Therefore it gives an error saying that it cannot connect to the container.

@SpringBootTest
@ExtendWith(SpringExtension.class)
@Testcontainers
@ActiveProfiles("test")
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public abstract class DatabaseIntegrationTest {
    // This guy is the problem. Remove him.
    @Container
    protected static final PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15");

    static {
        postgres.start();
    }
    
    @DynamicPropertySource
    static void registerDynamicProperties(DynamicPropertyRegistry registry) {
        registry.add("spring.datasource.url", postgres::getJdbcUrl);
        registry.add("spring.datasource.username", postgres::getUsername);
        registry.add("spring.datasource.password", postgres::getPassword);
    }
}
Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Container
  • User mentioned (0): @Test
  • User mentioned (0): @Container
  • Low reputation (1):
Posted by: Amer Mohammed