What is proper workaround for @BeforeAll in Kotlin

Grigory Konushev :

Currently JUNIT5 API only allows @BeforeAll only on the method that is static

so if if do like this and this will not compile:

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

so in order to have static method in Kotlin, I have to put in companion object like this:

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

This will compile, but I don't have access to variables from parent class. So what would be idiomatic way to invoke @BeforeAll of JUnit5 with Kotlin?

miensol :

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.

As stated in Spring documentation:

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=452831&siteId=1