1

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.

Olivier Grégoire
  • 33,839
  • 23
  • 96
  • 137

1 Answers1

3

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.)

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • 1
    Thanks for the `close()` tip, it's actually good to know that since Junit keeps by default strong references of the test instances for the whole run. In regards to Junit itself, you're right to doubt about the one instance per test method as it is entirely defined by the `Runner` used, even though the default one does that one instance per test. – Olivier Grégoire Nov 07 '15 at 11:26
  • Yeah, so you probably want to use `@Before` and `@After` to create/close your `FileSystem` so that you're doing everything correctly for JUnit. At some point I may create a JUnit Rule for Jimfs that does that for you. – ColinD Nov 07 '15 at 21:00
  • @ColinD how about from a performance standpoint? Is the creation of a JimFS file-system expensive? How does it handle threading for the WatchService; is it lazy such that if you don't use a watch, you don't allocate the Thread (and thus save the ~MB stack allocation)? Would you suggest trying to re-use a JimFS provided file system across test by doing something like `Files.delete(jimfs.getPath("/"))`? – Groostav Jul 03 '19 at 22:22