JUnit allows providing rules through a test class field or a getter method.
What you annotated is in Kotlin a property though, which JUnit won’t recognize.
Here are the possible ways to specify a JUnit rule in Kotlin:
Through an annotated getter method
From M13, the annotation processor supports annotation targets.
When you write
@Rule public val mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(javaClass<MainActivity>())
though, the annotation will use the
property target by default (not visible to Java).
You can annotate the property getter however, which is also public and thus satisfies JUnit requirements for a rule getter:
@get:Rule public val mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(javaClass<MainActivity>())
Alternatively, you can define the rule with a function instead of a property (achieving manually the same result as with
Through an annotated public field
Kotlin also allows since the beta candidate to deterministically compile properties to fields on the JVM, in which case the annotations and modifiers apply to the generated field. This is done using Kotlin’s
@JvmField property annotation as answered by @jkschneider.
Side note: be sure to prefix the
Rule annotation with an
@ character as it is now the only supported syntax for annotations, and avoid
@publicField as it will soon be dropped.