如何在Scala的specs2测试中使用jUnit的TemporaryFolder?

3

我正在使用Play框架编写一个测试,需要创建一个临时文件。

@RunWith(classOf[JUnitRunner])
class DiagnosticSpec extends Specification {
  @Rule
  val temporaryFolder: TemporaryFolder = new TemporaryFolder()

  "my test" should {
     "run with temporary file" in {
        val file = temporaryFolder.newFile()   // line.35
        // go on with the file
     }
  }
}

但是当我运行这个测试时,它总是抛出异常:
[error]     IllegalStateException: the temporary folder has not yet been created (MyTest.scala:35)

在specs2中可以使用它吗?如果不行,我该如何在specs2中创建一个临时文件,并在测试完成后自动删除它?

1个回答

3

你无法在specs2中使用JUnit规则来进行设置/拆卸。你需要使用 AroundExampleFixtureExample 来完成此操作:

trait TempFile extends AroundExample {
  // this code is executed "around" each example
  def around[R : AsResult](r: =>Result) = 
    val f = createFile("test")
    try AsResult(r)
    finally f.delete
}

class MySpec extends Specification with TempFile {
  "test" >> {
    // use the file here
    val file = new File("test")
    ...
  }
}

// Or
trait TempFile extends FixtureExample[File] {
  // this code is executed "around" each example
  def fixture[R : AsResult](f: File => R) = 
    val f = createFile("test")
    try AsResult(f(r))
    finally f.delete
}

class MySpec extends Specification with TempFile {
  // the file can be "injected" for each test
  "test" >> { file: File =>
    // use the file here
    ...
  }
}

更新

TemporaryFolder特性(Trait)更接近于原始的JUnit规则:

trait TemporaryFolder extends Specification {
  /** delete the temporary directory at the end of the specification */
  override def map(fs: => Fragments): Fragments = {
    super.map(fs.append(step(delete)))
  }

  lazy val tempDir = {
    val dir = File.createTempFile("test", "")
    dir.delete
    dir.mkdir
    dir
  }

  /** create a new file in the temp directory */
  def createNewFile = {
    val f = new File(tempDir.getPath+"/"+UUID.randomUUID.toString)
    f.createNewFile
    f
  }

  /** delete each file in the directory and the directory itself */
  def delete = {
    Option(tempDir.listFiles).map(_.toList).getOrElse(Nil).foreach(_.delete)
    tempDir.delete
  }
}

class MySpec extends Specification with TemporaryFolder {
  "test" >> {
    // use the file here
    val file = createNewFile
    ...
  }
}

谢谢,虽然不如我预期的好,但也许现在这是最好的解决方案。 - Freewind
你喜欢我刚刚添加的特性吗? - Eric

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接