简体   繁体   中英

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?

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());
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM