【发布时间】:2020-04-27 15:39:41
【问题描述】:
我无法在 JUnit 5 测试中初始化 @Autowired 成员。这是测试:
import org.amshove.kluent.`should be equal to`
import org.junit.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
@SpringBootTest
class SnackQueryResolverTest {
@TestConfiguration
class SnackQueryResolverTestConfig {
@Bean
fun snackQueryResolverFactory() = SnackQueryResolver()
}
@Autowired
private lateinit var snackQueryResolver: SnackQueryResolver
@Test
fun `snacks`() {
val snacks = snackQueryResolver.snacks()
snacks.size `should be equal to` 5
}
}
运行测试时我收到错误:
kotlin.UninitializedPropertyAccessException: lateinit property snackQueryResolver has not been initialized
如果我在构造过程中消除@Autowired 并实例化bean,测试运行良好:
@SpringBootTest
class SnackQueryResolverTest {
private val snackQueryResolver: SnackQueryResolver = SnackQueryResolver()
@Test
fun `snacks`() {
val snacks = snackQueryResolver.snacks()
snacks.size `should be equal to` 5
}
}
我错过了什么?
【问题讨论】: