【问题标题】:@Autowired member not initialized in a Junit 5 test written in Kotlin@Autowired 成员未在用 Kotlin 编写的 Junit 5 测试中初始化
【发布时间】: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
    }
}

我错过了什么?

【问题讨论】:

    标签: kotlin autowired junit5


    【解决方案1】:

    原来是一个小错误导致了问题 - IDE 代码完成时粗心。对于@Test,我正在导入:

    import org.junit.Test
    

    相反,这需要用于 JUnit 5 测试:

    import org.junit.jupiter.api.Test
    

    【讨论】:

    • 谢谢!我犯了同样的错误,把头发拔了!
    猜你喜欢
    • 1970-01-01
    • 2019-06-04
    • 2020-07-17
    • 1970-01-01
    • 2018-10-22
    • 2011-07-27
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    相关资源
    最近更新 更多