Currently the JUnit 5 API only allows @BeforeAll on a method that is static.

So if I do something like this, it will not compile:

@BeforeAll
  fun setup() {
    MockitoAnnotations.initMocks(this)
    mvc = MockMvcBuilders.standaloneSetup(controller).build()
}

In order to have a static method in Kotlin, I have to use companion object like this:

companion object {
    @JvmStatic
    @BeforeAll
    fun setup() {
      MockitoAnnotations.initMocks(this)
      mvc = MockMvcBuilders.standaloneSetup(smsController).build()
    }
}

这将进行编译,但我无法访问父类中的变量.那么,用Kotlin调用JUnit 5 @BeforeAll的惯用方法是什么呢?

推荐答案

As stated in the documentation of @BeforeAll:

Denotes that the annotated method should be executed before all @Test methods in the current class; analogous to JUnit 4’s @BeforeClass. Such methods must be static and are inherited.

The above is true for both Kotlin and Java. Keep in mind that by default Junit will create a separate instance of a test class per test case. It makes sense that @BeforeAll will only work with static methods since it's supposed to be invoked before any code of current test case. A static method has no access to instance members because it can be invoked without an instance.

如Spring文档中所述:

The "standaloneSetup" on the other hand is a little closer to a unit test.

The example shows that you should just use instance members like so:

class StandaloneTest {
  val smsController = ... // create instance of controller
  val MockMvcBuilders.standaloneSetup(smcController).build()
}

The usefulness of @BeforeAll is limited and should generally be avoided as it potentially encourages runtime dependencies between test cases.

Kotlin相关问答推荐

Kotlin编译器如何决定是否可以在任何给定点调用Suspend方法?

相当于roomdb中的DateTime Bigint列的是什么

用Quarkus和Reactor重写异步过滤器中的数据流

Kotlin接口方法默认值&;可传递依赖项

限制通用Kotlin枚举为特定类型

为什么Kotlin有次构造函数和init块?

列表在 android WebView 中没有正确迭代

TzdbZoneRulesProvider 在 java.time 中不工作

Kotlin:调用 CoroutineScope.launch 与在协程内启动之间的区别

判断 Kotlin 变量是否为函数

如何为 Kotlin 中的每个循环设置以避免越界异常

从带有 Room 和 Flows 的 SQLite 表中获取祖先树

T except one class

Saripaar formvalidation 在 kotlin 中第二次不起作用

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

如何在Kotlin中创建填充空值的通用数组?

添加抽象的私有getter和公共setter的正确方法是什么?

从命令行运行Java到Kotlin转换器?

Kotlin - 如果不为空,则使用修改后的 Obj props 覆盖 Obj props

Kotlin 的数据类 == C# 的 struct ?