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
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");
// ...
}
}
I think the best approche is te delete after JVM exit :
Path tmp = Files.createTempDirectory(null);
tmp.toFile().deleteOnExit();
Ensure that the method objectUnderTest.createFile(nameOfFile, textToWrite)
actually closes any opened streams?
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.