Search code examples
kotlinjunitjunit5

Non-static @RegisterExtension field in Kotlin 1.4 with JUnit5


When using Java and JUnit 5 I can register an extension using a non-static field like this:

@RegisterExtension
MyExtension myExtension = new MyExtension(...);

When I try to use Kotlin (1.4.10) instead, I cannot seem to get this to work. I've tried for example:

@RegisterExtension
val myExtension = MyExtension(...)

but it fails with:

org.junit.platform.commons.PreconditionViolationException: Failed to register extension via @RegisterExtension field [private final com.something.SomeTest.myExtension]: field must not be private.

when I try to run it.

If I try to add an @JvmField annotation:

@JvmField
@RegisterExtension
val myExtension = MyExtension(...)

it fails with a compile-time error instead:

JvmField can only be applied to final property

What I can do is to move it to a companion object:

companion object {
    @JvmField
    @RegisterExtension
    val myExtension = MyExtension(...)
}

now it works. But I cannot declare myExtension inside a companion object because the input to the constructor (...) is not available yet. I simply want it to be executed the same way as it would in the Java example presented above.

How can I do this in Kotlin (1.4)?


Solution

  • I had similar issue. I just had to make the field final in kotlin (in addition to annotatiing it with @JvmField):

    val wiremockPort = 8081
    
    @RegisterExtension
    @JvmField
    final val wireMockServer = WireMockTestRunner(wiremockPort)