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


0 votes
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 {
        private val postgres = PostgreSQLContainer<Nothing>("postgres:12.3").apply {

        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