Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...