Search code examples
scalaunit-testingfilesystemsscalatest

How To Create Temporary Directory in Scala Unit Tests


In scala how can a unit test create a temporary directory to use as part of the testing?

I am trying to unit test a class which depends on a directory

class UsesDirectory(directory : java.io.File) {
  ...
}

I'm looking for something of the form:

class UsesDirectorySpec extends FlatSpec {
  val tempDir = ??? //missing piece

  val usesDirectory = UsesDirectory(tempDir)

  "UsesDirectory" should {
    ...
  }
}

Also, any comments/suggestions on appropriately cleaning up the resource after the unit testing is completed would be helpful.

Thank you in advance for your consideration and response.


Solution

  • Krzysztof's answer provides a good strategy for avoiding the need for temp directories in your tests altogether.

    However if you do need UsesDirectory to work with real files, you can do something like the following to create a temporary directory:

    import java.nio.file.Files
    val tempDir = Files.createTempDirectory("some-prefix").toFile
    

    Regarding cleanup, you could use the JVM shutdown hook mechanism to delete your temp files.

    (java.io.File does provide deleteOnExit() method but it doesn't work on non-empty directories)

    You could implement a custom shutdown hook using sys.addShutdownHook {}, and use Files.walk or Files.walkTree to delete the contents of your temp directory.

    Also you may want to take a look at the better-files library, which provides a less verbose scala API for common files operations including File.newTemporaryDirectory() and file.walk()