Java FileSystem for simulating IOExceptions
- Add maven dependency:
<dependency>
<groupId>com.aerse</groupId>
<artifactId>mockfs</artifactId>
<version>1.4</version>
</dependency>
- Ensure code is ready
- Ensure
java.nio.file.Path
is used instead ofjava.io.File
. FileSystem is available only forPath
. - Ensure
Path::resolve(...)
is used instead ofjava.nio.file.Paths.get(...)
orPath::of(...)
. The latter usesFileSystems.getDefault()
instead of mocked - All
Path
should be created from the FileSystem usingFileSystem::getPath(...)
method.
- Setup the test
For example:
@Test(expected = IOException.class)
public void testFailingWrite() throws IOException {
byte[] data = createSampleData();
Path path = basePath.resolve(UUID.randomUUID().toString());
mockFs.mock(path, new FailingByteChannelCallback(5));
try (OutputStream w = Files.newOutputStream(path)) {
w.write(data);
}
}
- MockFileSystem could transparently pass the data to the default FileSystem. Just use
com.aerse.mockfs.NoOpByteChannelCallback
:
FileSystem fs = FileSystems.getDefault();
MockFileSystem mockFs = new MockFileSystem(fs);
mockFs.mock(path, new NoOpByteChannelCallback());
- Use
com.aerse.mockfs.FailingByteChannelCallback
for simulating IOExceptions after configurable number of bytes. - Mock read/write to every file in the directory. Just pass this directory to the
com.aerse.mockfs.MockFileSystem::mock(directoryToMock, ...)