John P
John P

Reputation: 1221

Spring boot unit test unable to share testcontainer between 2 test classes

I have a postgres test container class:

@Testcontainers
open class ContainerTest {
    companion object {
        @Container
        var postgresDBContainer = PostgreSQLContainer<Nothing>("postgres:13.4-alpine").apply {
            withExposedPorts(...)
            withDatabaseName(...)
            withUsername(...)
            withPassword(...)
        }

        @DynamicPropertySource
        @JvmStatic
        fun dbProperties(registry: DynamicPropertyRegistry) {
            registry.add("spring.datasource.url", postgresDBContainer::getJdbcUrl)
            registry.add("spring.datasource.password", postgresDBContainer::getPassword)
            registry.add("spring.datasource.username", postgresDBContainer::getUsername)
        }
    }
}

And I have 2 classes which extend this class (jupiter tests):

@SpringBootTest
@ActiveProfiles("test")
class TestClass1(
    @Autowired val service: SomeService
) : ContainerTest() {
    
    @Test
    fun `should return`() {
        ...
    }

}

And test class 2:

@SpringBootTest
@ActiveProfiles("test")
class TestClass2(
    @Autowired val service: SomeService2
) : ContainerTest() {
    
    @Test
    fun `should return`() {
        ...
    }

}

If I uncomment one of the classes, the build passes successfully, but when I build the project with both test classes, I am getting the following exception:

org.springframework.jdbc.CannotGetJdbcConnectionException at TestClass1.kt:23
        Caused by: java.sql.SQLTransientConnectionException at TestClass1.kt:23
            Caused by: org.postgresql.util.PSQLException at ConnectionFactoryImpl.java:319
                Caused by: java.net.ConnectException at PlainSocketImpl.java:-2

It seems that after all the tests of TestClass1 pass, the testcontainer is stopped, am I missing something?

How can I share the same testcontainer between test classes?

Thanks!

Upvotes: 1

Views: 1376

Answers (1)

Kevin Wittek
Kevin Wittek

Reputation: 1572

Indeed, the @Testcontainers annotation will call start/stop on a per-method or per-class basis on annotated container instances.

I would recommend to use Manual Lifecycle Control instead of the JUnit5 extension for controlling the container lifecycle.

Upvotes: 3

Related Questions