'Kotlin JUnit Rules

In Kotlin M13, this was an acceptable way to create a JUnit rule:

@Rule @publicField val temp = TemporaryFolder()

Now that @publicField has been deprecated, how else can this be achieved? The IDE hint suggests replacing @publicField with lateinit, but lateinit val's are no longer allowed, and I'm not sure this would help even if they were.



Solution 1:[1]

The answer as of Kotlin 1.0 is as follows:

@Rule @JvmField val temp = TemporaryFolder()

@JvmField exposes the backing field with the same visibility as the property, ergo a public field for the JUnit rule to use.

Solution 2:[2]

If anyone stumble's on this. I believe the approach with JJunit5 would be using @TempDir. https://junit.org/junit5/docs/5.4.2/api/org/junit/jupiter/api/io/TempDir.html

If you would need share the TempDir with tests, it must be a static property of the class. Static for java or within a companion Object for Kotlin

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2