如何将SpringBootTest的本地端口转发到测试配置

时间:2018-08-01 08:32:12

标签: kotlin spring-boot-test spring-boot-configuration

我目前正在为SpringBootTest实例的服务器端口注入而苦苦挣扎。我编写了一个测试配置类,我想在其中访问此端口。

测试配置类:

@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)
}

测试如下:

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

    @Autowired
    private lateinit var foo: Foo

    ...
}

现在的问题是,配置类中的端口始终收到零值。因为我没有得到null,这听起来好像是在获取端口,但是错误的是一个(我认为弹簧中的随机端口定义为零)。到目前为止,MyIntegrationTest类中的服务器端口评估工作正常。

有什么办法解决这个问题吗?

谢谢

3 个答案:

答案 0 :(得分:1)

在这种情况下,我们要做的是:

@Configuration
class Config {
    private lateinit var port: Int // 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
    }
}

答案 1 :(得分:0)

春季版本大于2.0.0的解决方案对我来说非常合适,

@Configuration
open class TestTemplateConfig {
    private var localPort: Int? = null

    @EventListener(WebServerInitializedEvent::class)
    fun onServletContainerInitialized(event: WebServerInitializedEvent) {
        localPort = event.webServer.port
    }
}

答案 2 :(得分:0)

对于Spring Boot 2.1.6,这对我有效:

import com.example.MyApplication
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.context.support.GenericApplicationContext
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig

@SpringJUnitConfig
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = [MyApplication::class])
class ApplicationStartsTest {
    @LocalServerPort
    protected var port: Int = 0

    @Autowired
    lateinit var context: GenericApplicationContext

    @Test
    fun `application context is initialized`() {
        assertTrue(::context.isInitialized, "Application context should have been injected")
    }

    @Test
    fun `web application port is assigned`() {
        assertTrue(port != 0, "web application port should have been injected")
    }
}