I have this working in Java:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class OtherTest {
@RegisterExtension
MyExtension myExtension = new MyExtension();
@Test
void myTest() {
System.out.println("my test");
}
}
However, the Kotlin version fails:
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
open class SomethingTest {
val something = Something()
@RegisterExtension
open var myExtension = MyExtension()
@Test
fun `test do something`(): Unit {
assert(something.doSomething())
}
// companion object {
// @JvmField
// @RegisterExtension
// val myExtension = MyExtension()
// }
}
with the exception
org.junit.platform.commons.PreconditionViolationException: Failed to register extension via @RegisterExtension field [private org.example.MyExtension org.example.SomethingTest.myExtension]: field must not be private.
at app//org.junit.platform.commons.util.Preconditions.condition(Preconditions.java:296)
The open‘s and var are attempts to get around this error. I suspect Junit is wrapping and trying to set the variable. Using ‘javap’ there’s definite differences between the Java and Kotlin version as the variable is only exposed through the getter/setters:
public class org.example.SomethingTest {
public org.example.SomethingTest();
public final org.example.Something getSomething();
public final org.example.MyExtension getMyExtension();
public final void setMyExtension(org.example.MyExtension);
public final void test do something();
}
The companion object (commented) is the workaround although I prefer not use static types.
Ideas?
My extension is simple enough:
class MyExtension : BeforeAllCallback, AfterAllCallback, BeforeEachCallback, AfterEachCallback {
override fun beforeAll(context: ExtensionContext?) {
println("beforeAll called")
}
override fun afterAll(context: ExtensionContext?) {
println("afterAll called")
}
override fun beforeEach(context: ExtensionContext?) {
println("beforeEach called")
}
override fun afterEach(context: ExtensionContext?) {
println("afterEach called")
}
}