Java NIO and Fake Filesystems

Jun 14, 2021 at 16:43

Java NIO

I need to write some unit tests against some code that used the filesystem.

Java has a few mock/in-memory filesystems, jimfs being one of the more popular ones.

It “mocks” out Path and the implementation of toFile() is to throw and UnsupportedOperationException because old-style Java operations are only supported on the ‘default’ filesystem, and thus cannot be ‘mocked’ out.

The technique we need, is to use java.nio.Paths and java.nio.Files.

Since we are working with Path objects and streams, the correct way to obtain a stream that is usable with both the default filesystem and something like jimfs is:

val fs = Jimfs.newFileSystem()
val path = fs.getPath("some/path")
val inputStream = Files.newInputStream(path)
// val outputStream = Files.newOutputStream(path)


In some cases you may want to disregard output, in which case Java supports OutputStream.nullOutputStream() which discards all bytes.