Ste*_* S. 5 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)
}
Run Code Online (Sandbox Code Playgroud)
测试看起来像这样:
@SpringBootJunit5Test
@TestAnnotation
@EnableTestCouchbase
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class MyIntegrationTest {
@LocalServerPort
var port: Int = 0
@Autowired
private lateinit var foo: Foo
...
}
Run Code Online (Sandbox Code Playgroud)
现在的问题是,我总是在配置类中收到端口的零值。因为我没有得到 null,这听起来像是它正在努力获取端口,但是错误的端口(我认为零是在 spring 中为随机端口定义的)。到目前为止,MyIntegrationTest 类中服务器端口的评估工作正常。
有什么想法可以解决这个问题吗?
谢谢
对于 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")
}
}
Run Code Online (Sandbox Code Playgroud)
这是我们在这种情况下所做的:
@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
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4058 次 |
最近记录: |