Simulate File in Java

Viewed 23577

I'm trying to write unit tests for a method that takes a String filename, then opens the file and reads from it. So, to test that method, I thought about writing a file, then calling my method. However, in the build farm, it is not possible to write files arbitrarily to disk. Is there a standard way to "simulate" having a real file in my unit test?

4 Answers

If you use JUnit, there is the TemporaryFolder. Files are deleted after the test. Example given on the page:

public static class HasTempFolder {
  @Rule
  public TemporaryFolder folder= new TemporaryFolder();

  @Test
  public void testUsingTempFolder() throws IOException {
      File createdFile= folder.newFile("myfile.txt");
      File createdFolder= folder.newFolder("subfolder");
      // ...
     }
 }

However, I have also used it for testing my Android class read/write capabilities like:

    [...]
    pw = new PrintWriter(folder.getAbsolutePath() + '/' + filename);
    pw.println(data);
Related