javajimfs

Do I have to clean my Jimfs FileSystem after each test?


I'm using Jimfs in my tests like this:

public class FooTest {
  private FileSystem fs = Jimfs.newFileSystem(Configuration.unix());
  private List<Path> paths = new ArrayList<>();
  private Path getPath(String first, String... more) {
    Path path = fs.getPath(first, more);
    paths.add(path);
    return path;
  }
  @After public void cleanPaths() {
    for (Path path: paths) {
      Files.walkFileTree(path, FileVisitors.DELETE);
    }
  }
  @Test public void bar() {
    Path baz = getPath("baz");
    // test using baz
  }
}

Now, we know that Jimfs is in memory. Do I really need to clean up the paths I created or can I just remove the @After method (and its associated mechanism)?

I clearly think it's the basic need why jimfs was created, but well... I'm adapting existing code and I suddenly became confused about this.


Solution

  • Since a new instance of FooTest is created for each test method (not sure if this is always true with JUnit, but I think it's at least true in the typical case), you're going to be getting a new FileSystem for each test as well unless you make that field static. So deleting the files you created after the test isn't necessary. What you might want to do, though, is close() the FileSystem after each test. That removes it from the map of open file systems immediately, allowing it to be garbage collected. (This isn't strictly necessary since the file system is stored in a weak reference there, but I think it's preferable anyway.)