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

Mhy*_*Mhy 6 junit spring kotlin spring-boot 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)
    }

}
Run Code Online (Sandbox Code Playgroud)

另一方面,我应该在这个方法中使用一些 Autowired 组件,但正如这里提到的在静态上下文中是不可能的,我得到了这个错误:

lateinit property repo has not been initialized
Run Code Online (Sandbox Code Playgroud)

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

Fab*_*mos 1

@BeforeAll我建议您切换到 Junit 5。它允许您在常规非静态方法上使用。另外,如果您使用 Junit 5 Spring 扩展,您\xe2\x80\x99 将能够将依赖项注入到您的@BeforeAll.

\n\n

如何更新 JUnit 版本将取决于您使用的构建工具(Maven 或 Gradle)。此外,您\xe2\x80\x99 需要替换@RunWith(SpringRunner::class)@ExtendWith(SpringExtension::class).

\n\n

src/test/resources/junit-platform.properties您\xe2\x80\x99还需要创建包含以下内容的属性文件: junit.jupiter.testinstance.lifecycle.default = per_class。有了这个,您将能够使用@BeforeAll非静态方法。

\n\n

看起来可能很多,但如果您使用 Kotlin 和 Spring Boot,JUnit 5 更适合。

\n\n

参考: 使用 Spring Boot 和 Kotlin 构建 Web 应用程序中的JUnit 5 测试

\n