Kotlin - 如何在 springBootTest 中管理@BeforeClass 静态方法
Kotlin - How to manage @BeforeClass static method in springBootTest
我想在我的 springBootTest 中有一个 @BeforeClass 方法,它应该是静态的并在 "companion object" 中声明。
@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
关于我应该如何处理这种情况有什么建议吗?
我建议您切换到 Junit 5。它允许您在常规非静态方法上使用 @BeforeAll
。此外,如果您使用 Junit 5 Spring 扩展,您将能够将依赖项注入 @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 更适合。
上使用 JUnit 5 进行测试
如果你不想升级到 JUnit5,你可以使用 @PostConstruct
它会产生同样的效果。示例
我想在我的 springBootTest 中有一个 @BeforeClass 方法,它应该是静态的并在 "companion object" 中声明。
@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
关于我应该如何处理这种情况有什么建议吗?
我建议您切换到 Junit 5。它允许您在常规非静态方法上使用 @BeforeAll
。此外,如果您使用 Junit 5 Spring 扩展,您将能够将依赖项注入 @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 更适合。
上使用 JUnit 5 进行测试如果你不想升级到 JUnit5,你可以使用 @PostConstruct
它会产生同样的效果。示例