【问题标题】:How to use jUnit's TemporaryFolder in scala's specs2 tests?如何在 scala 的 specs2 测试中使用 jUnit 的 TemporaryFolder?
【发布时间】:2014-08-26 09:55:44
【问题描述】:

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

@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中创建一个临时文件,并在测试后自动删除?

【问题讨论】:

    标签: file junit specs2


    【解决方案1】:

    您不能将 JUnit 规则与 specs2 一起使用来进行设置/拆卸。为此,您需要使用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
        ...
      }
    }
    

    【讨论】:

    • 谢谢,虽然没有我想象的那么好,但也许是目前最好的解决方案
    • 你喜欢我刚刚添加的特质吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-19
    • 2011-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多