Search code examples
scalaio

Creating temporary resource test files in Scala


I am currently writing tests for a function that takes file paths and loads a dataset from them. I am not able to change the function. To test it currently I am creating files for each run of the test function. I am worried that simply making files and then deleting them is a bad practice. Is there a better way to create temporary test files in Scala?

import java.io.{File, PrintWriter}

val testFile = new File("src/main/resources/temp.txt" )
val pw = new PrintWriter(testFile)

val testLines = List("this is a text line", "this is the next text line")
testLines.foreach(pw.write)
pw.close

// test logic here

testFile.delete()

Solution

  • I would generally prefer java.nio over java.io. You can create a temporary file like so:

    import java.nio.file.Files
    Files.createTempFile()
    

    You can delete it using Files.delete. To ensure that the file is deleted even in the case of an error, you should put the delete call into a finally block.