Kotlin and new ActivityTestRule : The @Rule must be public Kotlin and new ActivityTestRule : The @Rule must be public android android

Kotlin and new ActivityTestRule : The @Rule must be public


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

@Rulepublic 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:Rulepublic 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 @get:Rule).

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.


With Kotlin 1.0.0+, this works:

@Rule @JvmField val mActivityRule = ActivityTestRule(MainActivity::class.java)


Use this:

@get:Rulevar mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)