有没有办法在Scala中模拟文件系统进行单元测试

时间:2013-03-07 03:14:13

标签: scala filesystems mocking

我正在寻找一种在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。此外,PathResource等几个抽象似乎与FileSystem.default紧密相关。

我还在Scala-Tools中搜索了一些有趣的东西,但该项目似乎已经不存在了。

罗布

1 个答案:

答案 0 :(得分:2)

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

trait MyFileSystem { def getPath() }

然后,您可以使用真实的FileSystem和模拟版本来实现它。

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)