Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

scala - 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
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...