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

时间:2018-07-31 11:11:20

标签: 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)
    }

}

另一方面,我应该在此方法中使用一些自动装配的组件,但是如上所述here在静态上下文中是不可能的,并且出现了此错误:

lateinit property repo has not been initialized

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

2 个答案:

答案 0 :(得分:0)

我建议您切换到Junit5。它允许您在常规的非静态方法上使用@BeforeAll。另外,如果您使用Junit 5 Spring Extension,则可以将依赖项注入@BeforeAll中。

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

您还需要创建内容为src/test/resources/junit-platform.properties的属性文件junit.jupiter.testinstance.lifecycle.default = per_class。这样,您就可以在非静态方法上使用@BeforeAll

这似乎很多,但是如果您使用Kotlin和Spring Boot,则JUnit 5更合适。

参考:Building web applications with Spring Boot and Kotlin

上使用JUnit 5测试

答案 1 :(得分:0)

如果您不想升级到JUnit5,则可以使用@PostConstruct,它将具有相同的效果。示例here