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()
}
}
This will compile, but I don't have access to variables from the parent class. So what would be the idiomatic way to invoke JUnit 5 @BeforeAll
with Kotlin?
JUnit 5 has @TestInstance(PER_CLASS)
annotation that can be used for this purpose. One of the features that it enables is non-static BeforeAll
and AfterAll
methods:
@TestInstance(PER_CLASS)
class BeforeAllTests {
lateinit var isInit = false
@BeforeAll
fun setup() {
isInit = true
}
@TestFactory
fun beforeAll() = listOf(
should("initialize isInit in BeforeAll") {
assertTrue(isInit)
}
)
}
fun should(name: String, test: () -> Unit) = DynamicTest.dynamicTest("should $name", test)