4

I'm trying to integrate restartable Testcontainers into an application that uses JUnit and Kotlin.

The way I do it currently, is to have a companion class in every test suite where I set up the container and the Spring Boot properties, like so:

    companion object {
        @Container
        private val postgres = PostgreSQLContainer<Nothing>("postgres:12.3").apply {
            withDatabaseName("xxx")
            withExposedPorts(5432)
            withUsername("xxx")
        }

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

But since it's in a block that compiles to a static block, the container does not get restarted on every test (according to the behavior I'm observing and the official docs).

When I try to have the container outside of the companion object block, Spring cannot set up the dynamic props properly and throws java.lang.IllegalStateException: Mapped port can only be obtained after the container is started.

Trying to achieve my result with @DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD) had no effect on the behavior.

Cube.
  • 483
  • 6
  • 15

0 Answers0