Rob Conaway
Rob Conaway

Reputation: 141

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. 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. However, it doesn't look like all the core functionality in Scala-IO works with the FileSystem abstraction. In particular, I can't read from a Path or apply Path.asInput. Further, several of the abstractions like Path and Resource seem tightly bound to FileSystem.default.

I also googled some interesting stuff in Scala-Tools, but that project seems to be defunct.

Rob

Upvotes: 3

Views: 1851

Answers (1)

jwinder
jwinder

Reputation: 378

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.

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

class MyMainClass(fs: MyFileSystem)
main = new MyMainClass(new RealFileSystem(FileSystem.default))
test = new MyMainClass(new FakeFileSystem)

Upvotes: 3

Related Questions