Search code examples
scalaunit-testingjunitscalatest

Using JUnit @Rule with ScalaTest (e.g. TemporaryFolder)


I would like to be able to use JUnit rules such as TemporaryFolder or other TestRules we have already developed in-house. What is the best method to accomplish that? I'm aware of JUnitSuite but it doesn't seem to pick up the @Rule annotation. I would like to use a different ScalaTest suite anyway.

So my questions are:

  • Are JUnit rules supported by a ScalaTest suit?
  • If not, is there a library out there which would make using Junit TestRules possible?
  • If not, how to use JUnit TestRules in Scala tests?
  • Or is there a more appropriate Scala-specific approach for acomplishing what TemporaryFolder, or, e.g., Stefan Birkner's System Rules provide?

Here's what I tried with JUnitSuite:

class MyTest extends JUnitSuite {
  //@Rule
  //val temporaryFolder = new TemporaryFolder() // throws java.lang.Exception: The @Rule 'temporaryFolder' must be public.

  @Rule
  def temporaryFolder = new TemporaryFolder()

  @Test
  def test: Unit = {
    assert(temporaryFolder.newFile() !== null) // java.lang.IllegalStateException: the temporary folder has not yet been created
  }
}

Solution

  • You could solve the problem by creating a member field of type TemporaryFolder and returning this field value by the @Rule function.

    class MyTest extends JUnitSuite {
    
      val _temporaryFolder = new TemporaryFolder
    
      @Rule
      def temporaryFolder = _temporaryFolder
    
      @Test
      def test: Unit = {
        assert(temporaryFolder.newFile() !== null)
      }
    }