在 Scala 中创建临时资源测试文件

ric*_*ton 1 io scala

我目前正在为一个函数编写测试,该函数采用文件路径并从中加载数据集。我无法更改该功能。目前为了测试它,我正在为测试函数的每次运行创建文件。我担心简单地创建文件然后删除它们是一种不好的做法。有没有更好的方法在 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()
Run Code Online (Sandbox Code Playgroud)

Mat*_*ndt 5

我通常java.nio更喜欢java.io. 您可以像这样创建一个临时文件:

import java.nio.file.Files
Files.createTempFile()
Run Code Online (Sandbox Code Playgroud)

您可以使用 删除它Files.delete。为了确保即使在出现错误的情况下也能删除文件,您应该将调用放入delete一个finally块中。