2

I have an abstract controller test class and its inheritor with units, but I want to separate tests into different classes according to the controller method they are testing. Every time I create the second test-class and put a test in it I get the following error:

Failed to validate connection org.postgresql.jdbc.PgConnection@28806954 (This connection has been closed.). Possibly consider using a shorter maxLifetime value.

I have the following base class:

@SpringBootTest
@AutoConfigureMockMvc
@Testcontainers
public abstract class ControllerAbstractTest {
    @Container
    private final static PostgreSQLContainer postgreSQLContainer;

    static {
        postgreSQLContainer = new PostgreSQLContainer<>("postgres:13")
            .withDatabaseName("my-test-db")
            .withUsername("a")
            .withPassword("a");
        postgreSQLContainer.start();

        System.setProperty("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
        System.setProperty("spring.datasource.password", postgreSQLContainer.getPassword());
        System.setProperty("spring.datasource.username", postgreSQLContainer.getUsername());
    }
    // other methods

Tests work just fine in a single inheritor class.

I am using org.testcontainers:junit-jupiter:1.16.2, same version for postgresql and spring boot 2.5.6. @Test annotation is from org.junit.jupiter.api.Test

I have tried adding @Testcontainers to inheritors and removing it from the base test class, but it did not help.

1 Answers1

1

I prefer to start a container in a separate configuration so the test classes are not required to extend a specific abstract class.

/**
 * Starts a database server in a local Docker container.
 */
@TestConfiguration
public class TestDatabaseConfiguration {

    private static final PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer<>("postgres:13")
            .withDatabaseName("my-test-db")
            .withUsername("username")
            .withPassword("password");

    static {
        postgreSQLContainer.start();

        System.setProperty("spring.datasource.url", postgreSQLContainer.getJdbcUrl());
        System.setProperty("spring.datasource.password", postgreSQLContainer.getPassword());
        System.setProperty("spring.datasource.username", postgreSQLContainer.getUsername());
    }
}

Test classes that want to connect to the single shared database server are annotated with:

@Import(TestDatabaseConfiguration.class)
Chin Huang
  • 12,912
  • 4
  • 46
  • 47