[英]Is there a way to mock a filesystem for unit testing in Scala
I'm looking for a way to mock a filesystem in Scala. 我正在寻找一种在Scala中模拟文件系统的方法。 I'd like to do something like this: 我想做这样的事情:
class MyMainClass(fs: FileSystem) {
...
}
normal runtime: 正常运行时间:
val fs = FileSystem.default
main = new MyMainClass(fs)
test time: 测试时间:
val fs = new RamFileSystem
main = new MyMainClass(fs)
My examples look a lot like Scala-IO and I thought it might be my answer. 我的示例看起来很像Scala-IO,我认为这可能是我的答案。 However, it doesn't look like all the core functionality in Scala-IO works with the FileSystem
abstraction. 但是,Scala-IO的所有核心功能似乎都无法与FileSystem
抽象一起使用。 In particular, I can't read from a Path
or apply Path.asInput
. 特别是,我无法读取Path
或应用Path.asInput
。 Further, several of the abstractions like Path
and Resource
seem tightly bound to FileSystem.default
. 此外,一些抽象(如Path
和Resource
似乎与FileSystem.default
紧密绑定。
I also googled some interesting stuff in Scala-Tools, but that project seems to be defunct. 我还在Google Scala-Tools中搜索了一些有趣的东西,但是该项目似乎已经失效了。
Rob 抢
One option is to create your own abstraction. 一种选择是创建自己的抽象。 Something like this: 像这样:
trait MyFileSystem { def getPath() }
Then you can implement it with both a real FileSystem and a mocked version. 然后,您可以使用真实的FileSystem和模拟版本来实现它。
class RealFileSystem(fs: FileSystem) extends MyFileSystem {
def getPath() = fs.getPath()
}
class FakeFileSystem extends MyFileSystem {
def getPath() = "/"
}
And then MyMainClass can require a MyFileSystem instead of a FileSystem 然后MyMainClass可以要求使用MyFileSystem而不是FileSystem
class MyMainClass(fs: MyFileSystem)
main = new MyMainClass(new RealFileSystem(FileSystem.default))
test = new MyMainClass(new FakeFileSystem)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.