Deleting File and Directory in JUnit

前端 未结 4 1261
执笔经年
执笔经年 2021-02-09 08:20

I\'m writing a test for a method that creates a file in a directory. Here\'s what my JUnit test looks like:

  @Before
  public void setUp(){
      objectUnderTes         


        
相关标签:
4条回答
  • 2021-02-09 08:21

    Use the @Rule annotation and the TemporaryFolder classfor the folder that you need to delete.

    http://kentbeck.github.com/junit/javadoc/4.10/org/junit/Rule.html (404 not found)

    Update example of usage by http://junit.org/junit4/javadoc/4.12/org/junit/rules/TemporaryFolder.html:

    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");
        // ...
      }
    
    }
    
    0 讨论(0)
  • 2021-02-09 08:26

    I think the best approche is te delete after JVM exit :

    Path tmp = Files.createTempDirectory(null);
    tmp.toFile().deleteOnExit();
    
    0 讨论(0)
  • 2021-02-09 08:31

    Ensure that the method objectUnderTest.createFile(nameOfFile, textToWrite) actually closes any opened streams?

    0 讨论(0)
  • 2021-02-09 08:34

    This is how I usually clean up files:

    @AfterClass
    public static void clean() {
        File dir = new File(DIR_PATH);
        for (File file:dir.listFiles()) {
            file.delete();
        }
        dir.delete();
    }
    

    Your directory must be empty in order to delete it, make sure no other test methods are creating more files there.

    Ensure you are closing the FileWriter instance in a finally block.

    0 讨论(0)
提交回复
热议问题