In JUnit you can use @ClassRule to annotate an static field. How can I do this in Kotlin?
I tried:
object companion {
@ClassRule @JvmStatic
val managedMongoDb = ...
}
and
object companion {
@ClassRule @JvmField
val managedMongoDb = ...
}
but none of the last works because rule isn't executed.
I double checked that exactly same rule works fine without static context:
@Rule @JvmField
val managedMongoDb = ...
You are not using companion objects correctly. You are declaring an object (single instance of a class) called companion
instead of creating a companion object
inside of a class. And therefore the static fields are not created correctly.
class TestClass {
companion object { ... }
}
Is very different than:
class TestClass {
object companion { ... } // this is an object declaration, not a companion object
}
Although both are valid code.
Here is a correct working example of using @ClassRule
, tested in Kotlin 1.0.0:
class TestWithRule {
companion object {
@ClassRule @JvmField
val resource: ExternalResource = object : ExternalResource() {
override fun before() {
println("ClassRule Before")
}
override fun after() {
println("ClassRule After")
}
}
}
@Test fun testSomething() {
println("Testing...")
}
}
This outputs:
ClassRule Before
Testing...
ClassRule After
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With