spring - Kotlin - 如何在 springBootTest 中管理 @BeforeClass 静态方法

标签 spring spring-boot junit kotlin spring-boot-test

我想在我的 springBootTest 中有一个 @BeforeClass 方法,它应该是静态的并在“伴随​​对象”中声明。

@RunWith(SpringRunner::class)
@SpringBootTest
@ActiveProfiles("test")
open class MyTest {
companion object {

    @Autowired
    lateinit var repo: MyRepository

    @BeforeClass
    @JvmStatic
    fun X() {
        user = User()
        repo.save(user)
    }

}

另一方面,我应该在这个方法中使用一些 Autowired 组件,但正如前面提到的 here在静态上下文中是不可能的,我收到了这个错误:
lateinit property repo has not been initialized

关于我应该如何处理这种情况的任何建议?

最佳答案

如果您不想升级到 JUnit5,可以使用 @PostConstruct它会产生同样的效果。示例 here

关于spring - Kotlin - 如何在 springBootTest 中管理 @BeforeClass 静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51612019/

相关文章:

java - Camel 读取属性文件

mysql - 无法将mysql连接到spring boot项目

用于 Spring junit测试的mysql

java - 同时使用 junit 断言和 mockito 验证

java - 带有 Junit 4.7 "!!! JUnit version 3.8 or later expected:"的 IntelliJ IDEA

java - 如何确定我的 OpenJDK 库中使用的 xerces 版本?

java - 在 Spring Batch 中使用 getNamedParameterJdbcTemplate() 方法运行 JUnit 时出现问题

java - 是否可以在 spring-boot 中更改/health 端点?

java - Docker compose 以状态 1 退出,spring boot 在日志中启动并立即结束,但无法识别故障原因

java - 如何在Spring Boot测试中打印@sql注释中脚本文件的完整路径