Barracuda
Barracuda

Reputation: 567

Spring boot multiple tests with testcontainers

I am trying to use Spring Boot Tests with test containers. I wrote an abstract integration tests that all integration tests are using.

@Testcontainers
@Transactional
@ActiveProfiles("test")
@SpringBootTest
@TestConstructor(autowireMode = TestConstructor.AutowireMode.ALL)
abstract class AbstractITest : AbstractTest(){

    companion object{

        @Container
        @ServiceConnection(type = [JdbcConnectionDetails::class])
        val mysql = MySQLContainer("mysql:latest").withInitScript("test.sql")

    }

}

When I run every test class individually through intellij, it runs normally. But when I try to run all tests together, I get connection timeout on the second class executed. When I debug, I notice that my hikari connection pool is configured with a jdbc url of the previous test run. For example, first run uses 33835 port and the second uses 338836, but the hikari connection pool in the second run is configured with the previous 33835 port. I think I configured everything as shown in the official documentation of spring boot. Why is this problem occurring?

In logs, i can see a log

2023-10-26T19:12:34.718+03:00  INFO 46718 --- [    Test worker] tc.mysql:latest                          : Container is started (JDBC URL: jdbc:mysql://localhost:32847/test)

but in connection pool, i see port 32846.

I am using spring boot 3.1.4.

Upvotes: 3

Views: 2166

Answers (2)

Ravi Soni
Ravi Soni

Reputation: 1343

Configure abstract class this way and then extend other classes which requires db access.

@Testcontainers
@Slf4j
public abstract class AbstractMySqlDatabaseTests {

    protected static final MySQLContainer<?> mysqlContainer;
    static {
        mysqlContainer = new MySQLContainer<>("mysql:5.7");
        mysqlContainer.start();
    }

    @DynamicPropertySource
    static void configureProperties(DynamicPropertyRegistry registry) {
        // your code to manipulate app properties
    }

Upvotes: 2

Yahia Mohamed
Yahia Mohamed

Reputation: 1

You need to add this annotation before your abstarct class definition @TestConfiguration(proxyBeanMethods = false) This will create a service connection details everytime a connection is required beacuse we set proxyBeanMethods to false, i.e.: prototype not singleton.

Read about proxyBeanMethods here: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/context/annotation/Configuration.html#proxyBeanMethods()

Upvotes: 0

Related Questions