javaapache-commons-io

How do I unit-test saving file to the disk with FileUtils?


I know this variation has been asked before.

But, One of my functions is using Common's FileUtils. Here, it only takes File object and String. Is there any way to unit test this?


Solution

  • Of course. Use a temporary folder, save your file there, and delete the folder after the test.

    If you use JUnit, look at the TemporaryFolder JUnit rule (it creates a temp folder for you and takes care of the deleting).

    Example code:

    public class YourTest {
      @Rule
      public TemporaryFolder folder= new TemporaryFolder();
    
      @Test
      public void testUsingTempFolder() throws IOException {
          String filePath = folder.newFile("myfile.txt").getAbsolutePath();
          FileUtils.writeFile(filePath, "some String");
          assertTrue(new File(filePath).exists());
      }
    }