有没有一种方法在Scala中模拟文件系统进行单元测试?

3

我正在寻找一种在Scala中模拟文件系统的方法。我想做类似于这样的事情:

class MyMainClass(fs: FileSystem) {
   ...
}

正常运行时:
val fs = FileSystem.default
main = new MyMainClass(fs)

测试时间:

val fs = new RamFileSystem
main = new MyMainClass(fs)

我的例子看起来很像Scala-IO,我以为它可能是我的答案。但是,Scala-IO中的所有核心功能似乎都不适用于FileSystem抽象。特别是,我无法从Path读取或应用Path.asInput。此外,几个抽象,如Path和Resource,似乎与FileSystem.default紧密绑定。
我还在谷歌上搜索了一些有趣的Scala-Tools内容,但该项目似乎已经停止维护。
Rob

Scala-Tools本身已经不存在了,但是那些在那里托管的项目已经迁移到其他地方了。 - undefined
1个回答

3

一种选择是创建自己的抽象层。可以像这样:

trait MyFileSystem { def getPath() }

然后你可以使用真实的文件系统和模拟版本来实现它。

class RealFileSystem(fs: FileSystem) extends MyFileSystem {
  def getPath() = fs.getPath()
}

class FakeFileSystem extends MyFileSystem {
  def getPath() = "/"
}

然后,MyMainClass可以要求一个MyFileSystem而不是FileSystem。
class MyMainClass(fs: MyFileSystem)
main = new MyMainClass(new RealFileSystem(FileSystem.default))
test = new MyMainClass(new FakeFileSystem)

如果我找不到我想要的东西,这是一个很好的折衷办法。也许我可以封装Scala IO来获得我想要的模拟,同时仍然利用Scala IO中的Scala习惯用法。 - undefined
我也被告知Java 7或8可能有我所需的内容。尽管我更喜欢符合惯用法的Scala,但我可能会研究一下Java 7或8。 - undefined

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