Geob-o-matic Geob-o-matic - 3 months ago 32
Android Question

Kotlin and new ActivityTestRule : The @Rule must be public

I'm trying to make UI test for my android app in Kotlin. Since the new system using ActivityTestRule, I can't make it work: it compiles correctly, and at runtime, I get:

java.lang.Exception: The @Rule 'mActivityRule' must be public.
at org.junit.internal.runners.rules.RuleFieldValidator.addError(
at org.junit.internal.runners.rules.RuleFieldValidator.validatePublic(
at org.junit.internal.runners.rules.RuleFieldValidator.validateField(
at org.junit.internal.runners.rules.RuleFieldValidator.validate(
at org.junit.runners.BlockJUnit4ClassRunner.validateFields(
at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(
at org.junit.runners.ParentRunner.validate(
at org.junit.runners.ParentRunner.<init>(
at org.junit.runners.BlockJUnit4ClassRunner.<init>(
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(
at org.junit.runner.Computer.getRunner(
at org.junit.runner.Computer$1.runnerForClass(
at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(
at org.junit.runners.model.RunnerBuilder.runners(
at org.junit.runners.model.RunnerBuilder.runners(
at org.junit.runners.Suite.<init>(
at org.junit.runner.Computer.getSuite(

Here is how I declared mActivityRule:

public class RadisTest {

public val mActivityRule: ActivityTestRule<MainActivity> = ActivityTestRule(javaClass<MainActivity>())


It is already public :/


JUnit allows to provide 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

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:

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 @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.