22

I tried to use a unit test rule annotation and Android Studio didn't highlight any error here:

@Rule val htmlManager = HtmlManager()

However after executing the test following error happens:

org.junit.internal.runners.rules.ValidationError: The @Rule 'htmlManager' must be public.

How to fix this?

donfuxx
  • 11,277
  • 6
  • 44
  • 76

3 Answers3

51

The solution is to apply @Rule annotation to property getter:

@get:Rule
val htmlManager = HtmlManager()

more detail here: https://kotlinlang.org/docs/reference/annotations.html#java-annotations

see the fixed test case code here in my open-source project: https://github.com/appham/Sharemarks/commit/310c115d5a820be900abc321cc061aeab7af2e5a#diff-5e1e851ef5b9bb333abb96dec3199a94

donfuxx
  • 11,277
  • 6
  • 44
  • 76
9

You can also use the @JvmField annotation

@Rule @JvmField 
val htmlManager = HtmlManager()
Steve
  • 533
  • 3
  • 7
0

Another solution is:

val htmlManager = HtmlManager()
    @Rule get() = field
Marian Paździoch
  • 8,813
  • 10
  • 58
  • 103