Search code examples
kotlinspring-boot-testspring-boot-configuration

How to forward the local port of a SpringBootTest to a test configuration


I am currently struggling with the server port injection of the SpringBootTest instance. I've written a test configuration class where I would like to access this port.

Test Configuration class:

@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE)
@Retention(AnnotationRetention.RUNTIME)
@Import(value = [TestTemplateConfig::class])
annotation class TestAnnotation

@Configuration
open class TestTemplateConfig {
    @Value("\${server.port}")
    private var localPort: Int? = null

    @Bean
    open fun foo() = Foo(localPort)
}

The Test looks like this:

@SpringBootJunit5Test
@TestAnnotation
@EnableTestCouchbase
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MyIntegrationTest {
    @LocalServerPort
    var port: Int = 0

    @Autowired
    private lateinit var foo: Foo

    ...
}

The problem now is, that I always receive a value of zero for the port in the configuration class. Because I don't get null this sounds like it is working to get the port but the wrong one (I think zero is defined for a random port in spring). The evaluation of the server port in the MyIntegrationTest class is working properly so far.

Any ideas to fix this?

Thanks


Solution

  • Here's what we did in this case:

    @Configuration
    class Config {
        private lateinit var port: java.lang.Integer // declare a var to store the port
        
        @EventListener // subscribe to servlet container initialized event
        fun onServletContainerInitialized(event: EmbeddedServletContainerInitializedEvent) {
            port = event.embeddedServletContainer.port // when event is fired, extract the port for that event
        }
    }