Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...