Issue
I found two ways to create temporary directories in JUnit.
Way 1:
@Rule
public TemporaryFolder tempDirectory = new TemporaryFolder();
@Test
public void testTempDirectory() throws Exception {
tempDirectory.newFile("test.txt");
tempDirectory.newFolder("myDirectory");
// how do I add files to myDirectory?
}
Way 2:
@Test
public void testTempDirectory() throws Exception {
File myFile = File.createTempFile("abc", "txt");
File myDirectory = Files.createTempDir();
// how do I add files to myDirectory?
}
As the comment above mentions, I have a requirement where I want to add some temporary files in these temporary directories. Run my test against this structure and finally delete everything on exit.
How do I do that?
Solution
You can do it the same way you do it for real folders.
@Rule
public TemporaryFolder rootFolder = new TemporaryFolder();
@Test
public void shouldCreateChildFile() throws Exception {
File myFolder = rootFolder.newFolder("my-folder");
File myFile = new File(myFolder, "my-file.txt");
}
Answered By - Sasha Shpota
Answer Checked By - Candace Johnson (JavaFixing Volunteer)