Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

Making Testcontainers restartable with Kotlin, JUnit, and Spring Boot

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...